简体   繁体   中英

TypeError: start() takes exactly 1 argument (0 given)?

I have something like this:

class thread1(threading.Thread):
    def __init__(self):
        file = open("/home/antoni4040/file.txt", "r")
        data = file.read()
        num = 1
        while True:
           if str(num) in data:
               clas = ExportToGIMP
               clas.update()
           num += 1     
thread = thread1
        thread.start()
        thread.join()

And I get this error:

TypeError: start() takes exactly 1 argument (0 given)

Why?

thread = thread1 needs to be thread = thread1() . Otherwise you're trying to call methods on the class, rather than an actual instance of the class.


Also, don't override __init__ on a Thread object to do your work - override run .

(While you can override __init__ to do setup, that's not actually run in a thread, and needs to call super() as well.)


Here's how your code should look:

class thread1(threading.Thread):
    def run(self):
        file = open("/home/antoni4040/file.txt", "r")
        data = file.read()
        num = 1
        while True:
           if str(num) in data:
               clas = ExportToGIMP
               clas.update()
           num += 1     

thread = thread1()
        thread.start()
        thread.join()

When you write

thread = thread1

you are assigning to thread the class thread1 , ie thread becomes synonymous of thread1 . For this reason, if you then write thread.start() you get that error - you are calling an instance method without passing self

What you actually want is to instantiate thread1 :

thread = thread1()

so thread becomes an instance of thread1 , on which you can call instance methods like start() .

By the way, the correct way to use threading.Thread is to override the run method (where you write the code that is to be run in another thread), not (just) the constructor.

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