简体   繁体   English

Python-函数不是“全局”函数,因此无法在线程类中调用

[英]Python - Function isn't 'Global' and so can't be called within Threading Class

So, first off here's my code: 因此,首先是我的代码:

import threading

print "Press Escape to Quit"

class threadOne(threading.Thread): #I don't understand this or the next line
    def run(self):
        setup()

    def setup():
        print 'hello world - this is threadOne'


class threadTwo(threading.Thread):
    def run(self):
        print 'ran'

threadOne().start()
threadTwo().start()

So, the problem is that within my class 'threadOne' the run function runs (as that is called by the threading module) but from there I can not called any other functions. 因此,问题在于我的类“ threadOne”中运行了运行函数(由线程模块调用),但是从那里我无法调用任何其他函数。 That includes if I make more functions beneath the setup() function. 这包括是否要在setup()函数下创建更多函数。 For example above, in my run(self) function I try and call setup() and get 'NameError: global name 'setup' is not defined'. 例如,在上面的示例中,我在run(self)函数中尝试调用setup()并获取“ NameError:全局名称'setup'未定义”。

Does anybody have any ideas or can they explain this to me? 有人有任何想法或可以向我解释吗?

Sam 山姆

setup is a method of your Thread instance. setup是您的Thread实例的一种方法。 Therefore, you call it with self.setup() rather than setup() . 因此,您可以使用self.setup()而不是setup()调用它。 The latter is trying to call a global function named setup which does not exist. 后者正在尝试调用不存在的名为setup的全局函数。

Since setup() is an instance method, it must accept self as its first parameter as well. 由于setup()是实例方法,因此它也必须接受self作为其第一个参数。

I assume you meant to do the following: 我认为您打算执行以下操作:

class threadOne(threading.Thread): #I don't understand this or the next line
    def run(self):
        self.setup()

    def setup(self):
        print 'hello world - this is threadOne'

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

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