所以当我在一个类内部的另一个函数内部调用一个函数时,我遇到了一个更大的代码问题。在代码中:
#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类不能那样工作。
答案 0 :(得分:3)
问题编辑后更新:
查看此链接,了解如何制作“封闭式”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
函数具有相同的缩进级别。
答案 1 :(得分:1)
缩进级别已关闭。您正在定义运行函数的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()
答案 2 :(得分:0)
似乎在定义之前调用函数。我认为关闭可以帮助你:
def run(self):
print "I will now square your number"
print "Your number squared is: "
def calculate():
return self.number**2
print calculate()
答案 3 :(得分:0)
当你在函数内部定义一个函数时,就不需要使用'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()