【问题标题】:TypeError: start() takes exactly 1 argument (0 given)?TypeError: start() 只需要 1 个参数(给定 0)?
【发布时间】:2012-10-19 04:39:54
【问题描述】:

我有这样的事情:

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)

为什么?

【问题讨论】:

    标签: python multithreading arguments typeerror


    【解决方案1】:

    thread = thread1 必须是 thread = thread1()。否则你会尝试调用类的方法,而不是类的实际实例。


    另外,不要覆盖 Thread 对象上的 __init__ 来完成您的工作 - 覆盖 run

    (虽然您可以覆盖__init__ 来进行设置,但这实际上并没有在线程中运行,并且还需要调用super()。)


    您的代码应如下所示:

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

    【讨论】:

      【解决方案2】:

      当你写作时

      thread = thread1
      

      您正在分配给threadthread1,即thread 成为thread1 的同义词。出于这个原因,如果你然后写 thread.start() 你会得到那个错误 - 你正在调用一个实例方法而不传递 self

      你真正想要的是实例化 thread1:

      thread = thread1()
      

      所以thread 成为thread1 的一个实例,您可以在其上调用start() 等实例方法。

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

      【讨论】:

        猜你喜欢
        • 2016-08-17
        • 1970-01-01
        • 2019-03-24
        • 2018-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多