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)

Answers


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()

Need Your Help

Get value from selected picker row in WatchKit 2

swift watchkit xcode7 watch-os-2

I'm using Xcode 7 and I'm trying to pass a value from the picker to another function when a button is pressed. Is it possible to get the value of the row that is currently selected in the picker? O...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.