简体   繁体   English

Python脚本返回函数未定义错误

[英]Python script is returning function not defined error

I am writing a python class and trying to call a function from another function in the class but I am running into an error. 我正在编写一个python类,并试图从该类中的另一个函数调用一个函数,但是我遇到了一个错误。 NameError: name 'bobfunction' is not defined . NameError: name 'bobfunction' is not defined My call to the class works, even the call to method/function job works. 我对类的调用有效,甚至对方法/函数作业的调用也有效。 When job tries to call bobfunction I get the error message. job尝试调用bobfunction我收到错误消息。 removing the call to bobfunction works. 删除对bobfunction的调用即可。 So how do I call the bobfunction from the job function? 那么如何从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'

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

Python uses the keyword self to refer to class methods and variables of the same class. Python使用关键字self来引用同一类的类方法和变量。 It is similar to this keyword in other languages. 在其他语言中,它与this关键字相似。 (Not the same though) . (虽然不一样)。 If you end up defining a variable in your __init__ function , you can also use it with self.variable_name in other functions. 如果最终在__init__函数中定义了一个变量,则还可以在其他函数self.variable_name其与self.variable_name一起使用。

You should try to run it with stuff.bobfunction(self,"test data") Because bobfunction was situated in class stuff, you need to write class' name before function's name. 您应该尝试使用stuff.bobfunction(self,“ test data”)运行它。由于bobfunction位于类stuff中,因此您需要在函数名称之前写出类名称。 Self in parentheses must send the name of self. 括号内的自我必须发送自我的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM