我试图从我的主函数中调用同一个类中的不同函数,我似乎可以找出错误所在。
我不断收到与未定义函数相关的错误,但我不知道如何解决它:
NameError: global name 'results' is not defined
class Darts:
def main() :
print results()
def results() :
round_result_totals = "Stuff"
return round_result_totals
#RUNNING CODE
main()
最佳答案
确保您定义正确 self
在您的函数中,并在执行其他操作之前先初始化对象。您不能只调用 function
来自class
无需创建 instance
其中class
并调用 function
从那instance
(不是类(class))。通常你想要一个__init__
在你的Python类中。
class Darts:
def __init__(self):
pass
def main(self):
print(self.results())
def results(self):
round_result_totals = "Stuff"
return round_result_totals
Dart1 = Darts()
Dart1.main()
如果你想使用变量,self
对于封装也至关重要。
class Darts:
def __init__(self):
self.a = 500
def main(self):
self.a += 1
print(self.a)
Dart1 = Darts()
Dart1.main()
关于function - 名称错误 : global name not defined when calling method inside class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29886867/