function - 名称错误 : global name not defined when calling method inside class

标签 function python-2.7 runtime-error

我试图从我的主函数中调用同一个类中的不同函数,我似乎可以找出错误所在。

我不断收到与未定义函数相关的错误,但我不知道如何解决它:

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/

相关文章:

r - DCC-GARCH的实现

c - 函数中标识符列表和参数列表的区别?

javascript - 如何通过引用将属性传递给 javascript 函数?

c++ - 使用给定参数调用构造函数的可变参数函数

python - 日期时间对象上的 Django F 表达式

python - 使用计算 GCD - Python 函数返回

python - 运行时警告 : invalid value encountered in maximum

mysql - 将列中的所有文本转换为 MySql 中的驼峰式大小写

python - 为什么这不会使用 python 插入到我的数据库中?

java - hadoop运行程序出错?