【问题标题】:Python script is returning function not defined errorPython脚本返回函数未定义错误
【发布时间】:2019-03-30 10:59:13
【问题描述】:

我正在编写一个 python 类并试图从该类中的另一个函数调用一个函数,但我遇到了一个错误。NameError: name 'bobfunction' is not defined。我对课堂的调用有效,甚至对方法/函数作业的调用也有效。当job 尝试调用bobfunction 时,我收到错误消息。删除对bobfunction 的调用有效。那么如何从 job 函数中调用 bobfunction 呢?

class stuff():
    def __init__(self):
        #setup stuff

     def bobfunction(self,junk):
         print("should work")
         return ''

      def job(self,data):
          bobfunction('test data')
          return 'other junk'

【问题讨论】:

  • 您的缩进似乎偏移了。工作职能中的def 应与bobfunction 中的def 对齐

标签: python-3.x class methods


【解决方案1】:

使用self.bobfunction("test data") 运行它

Python 使用关键字self 来引用同一类的类方法和变量。它类似于其他语言中的this 关键字。 (虽然不一样)。如果您最终在 __init__ 函数中定义了一个变量,您也可以在其他函数中将它与 self.variable_name 一起使用。

【讨论】:

    【解决方案2】:

    您应该尝试使用 stuff.bobfunction(self,"test data") 运行它 因为 bobfunction 位于类的东西中,所以你需要在函数名之前写类名。 括号中的self必须发送self的名字。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-13
      • 2016-06-20
      • 1970-01-01
      • 2014-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-01
      相关资源
      最近更新 更多