简体   繁体   中英

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. That includes if I make more functions beneath the setup() function. For example above, in my run(self) function I try and call setup() and get 'NameError: global name 'setup' is not defined'.

Does anybody have any ideas or can they explain this to me?

Sam

setup is a method of your Thread instance. Therefore, you call it with self.setup() rather than setup() . The latter is trying to call a global function named setup which does not exist.

Since setup() is an instance method, it must accept self as its first parameter as well.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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