所以我有一个更大的代码块的问题,我得到一个错误消息,当我调用一个函数内部的另一个函数是在一个类。代码中:
#Test program to solve problems.
class Foo(object):
def __init__(self, number):
self.number = number
def run(self):
print "I will now square your number"
print "Your number squared is: "
print self.calculate()
#This squares the number
def calculate(self):
return self.number**2
if __name__ == "__main__":
test = Foo(input("Choose a number: "))
print test.run()
我提出一个"AttributeError: Foo
没有属性calculate
",但我不明白为什么?我叫calculate
错误抛出这个错误吗?
编辑
所以我知道,如果我改变缩进或calculate
它的工作,但我想知道,无论如何,让它工作,因为它目前是与calculate
缩进在run
或做python类不工作的方式。
问题编辑后更新:
查看这个展示如何创建"闭包"的链接https://stackoverflow.com/a/4831750/2459730
这就是你所说的函数中的函数
def run(self):
def calculate(self): # <------ Need to declare the function before calling
return self.number**2
print "I will now square your number"
print "Your number squared is: "
print self.calculate() # <---- Call after the function is declared
提问前编辑:您的calculate
函数没有正确缩进。
def run(self):
print "I will now square your number"
print "Your number squared is: "
print self.calculate()
#This squares the number
def calculate(self): # <----- Proper indentation
return self.number**2 # <------ Proper indentation
calculate
函数应该具有与run
函数相同的缩进级别
关闭缩进。在run函数中定义了calculate INSIDE,而不是在类中定义。
class Foo(object):
def __init__(self, number):
self.number = number
def run(self):
print "I will now square your number"
print "Your number squared is: "
print self.calculate()
#This squares the number
def calculate(self): #NOTE THE INDENTATION DIFFERENCE
return self.number**2
if __name__ == "__main__":
test = Foo(input("Choose a number: "))
print test.run()
似乎你调用函数之前,它被定义。我认为结束语应该对你有帮助:
def run(self):
print "I will now square your number"
print "Your number squared is: "
def calculate():
return self.number**2
print calculate()
当你在函数内部定义一个函数时,不需要使用'self'在内部函数中,定义函数后调用函数。所以你可以把代码写成
class Foo(object):
def __init__(self, number):
self.number = number
def run(self):
#This squares the number
def calculate():
return self.number**2
print "I will now square your number"
print "Your number squared is: "
print calculate()
if __name__ == "__main__":
test = Foo(int(input("Choose a number: ")))
print test.run()
问题就是你不能那样做。这看起来很诱人,因为您可以在类之外这样做,这样可以使您的代码更干净,但在类中,您不能这样做。