simple passing of variables to classes
Why doesn't this work ?
class spin(threading.Thread): def __init__(self): super(spin,self).__init__() self._stop = False def run (self,var): self.var=var print self.var def echo (self,var): self.var=var print self.var if __name__ == '__main__': s = spin() s.start('hello')
but this does?
s = spin() s.echo('hello')
Im guessing its because the start sequence needs to be defined in the init ? but not sure how. someone asked for error codes from this:
s.start('hello') TypeError: start() takes exactly 1 argument (2 given)
The reason s.start('hello') does not work is that the inherited Threadin.start() method takes no arguments other than self.
Calling s.echo('hello') does appear to work, but it calls the function in the context of the main thread instead of spawning a new thread.
One way to fix your code is by supplying var to the constructor:
import threading class Spin(threading.Thread): def __init__(self,var): super(Spin,self).__init__() self.var = var def run(self): print self.var if __name__ == '__main__': s = Spin('hello') s.start() s.join()