为什么python在这个类的第二个方法中抛出错误?
class Lutany:
formulaa = 0
formulab = 0
def __init__(self,num):
self.num = num
self.formulaa = self.formulaA()
self.formulab = self.formulaB
def formulaA(self):
q = 0
num = self.num
while num > 0 :
q += num + (num - 1)
num = num - 1
return q
self.formulab = formulaB()
def formulaB(self):
num = self.num
q = 0
while num > 0 :
q = q + (num * num)
num = num - 1
return (0.5 * q)
if(__name__ == '__main__'):
l = Lutany(675)
p = l.formulaa
q = l.formulab
print " FormunlA returned " , str(p) , " for 675 "
print " FormulaB returned " , str(q) , " for 675 "
运行时出现以下错误:
~$ python lutany.py
Traceback (most recent call last):
File "lutany.py", line 30, in <module>
l = Lutany(675)
File "lutany.py", line 7, in init
self.formulab = self.formulaB
AttributeError: Lutany instance has no attribute 'formulaB'
答案 0 :(得分:2)
您已经过多地缩进了formulaB()
方法的块(尽管对该问题的编辑已经破坏了这一点的证据)。确保它位于类缩进正下方的缩进级别,而不是前一个方法的缩进级别。
答案 1 :(得分:0)
当你说,在formalaA self.formulab = formulaB()
你的意思是self.formulab = self.formulaB()
?
答案 2 :(得分:0)
您在这里遗漏了括号:self.formulab = self.formulaB
。应该是self.formulab = self.formulaB()
。