2012-10-29 90 views
1

我有这样的事情:TypeError:start()只需要1个参数(0给定)?

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

我得到这个错误:

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

为什么?

回答

5

thread = thread1需要为thread = thread1()。否则,你试图调用类的方法,而不是类的实际实例。


另外,不要忽略__init__一个Thread对象做你的工作 - 覆盖run

(虽然你可以覆盖__init__做设置,实际上并不是在一个线程中运行,并且需要调用super()为好。)


这里怎么你的代码看起来应该'S:

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

当你写

thread = thread1 

要分配到thread类别thread1,即thread成为thread1的同义词。出于这个原因,如果你再写入thread.start()你得到这个错误 - 你没有通过self

调用一个实例方法,你真正想要的是什么实例化thread1

thread = thread1() 

所以thread变为实例thread1,您可以在其上调用实例方法,如start()

顺便说一下,使用threading.Thread的正确方法是覆盖run方法(在其中编写要在另一个线程中运行的代码),而不仅仅是构造函数。

相关问题