Python XX实例没有属性YY

我有这个noob错误,

   l = instanciaHagale.multiplicaMethod() AttributeError: Hagale instance has no attribute 'multiplicaMethod'

我的代码:

class Hagale :
    def __init__(self, a):
        self.a = a 
        print self.a 

        self.sumaleAlgo = self.a+34543 #variable creada on the fly!

        def multiplicaMethod (self):

            return 'self.cuadradoReal'
            #self.cuadradoReal = self.a * 2

instanciaHagale = Hagale(345)

print instanciaHagale.sumaleAlgo #acceso a las variables de mi objeto! 

l = instanciaHagale.multiplicaMethod()

print l 

最佳答案

    def __init__(self, a):
        # ...

        def multiplicaMethod (self):

最后一个def缩进了错误.它突然出现,因此它与def __init __(self,a):处于同一级别,如下所示:

class Hagale(object):
    def __init__(self, a):
        self.a = a 
        print self.a 
        self.sumaleAlgo = self.a+34543 #variable creada on the fly!

    def multiplicaMethod (self): # <-- moved to the left
        return 'self.cuadradoReal'

另请注意,您的代码使用classic classes.这可能不是您想要的,但这是一个简单的修复 – 只需从对象继承.

点赞