4

我正在尝试使用提供的StoppableThread课程作为另一个问题的答案

import threading

# Technique for creating a thread that can be stopped safely
# Posted by Bluebird75 on StackOverflow
class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self):
        super(StoppableThread, self).__init__()
        self._stop = threading.Event()

    def stop(self):
        self._stop.set()

    def stopped(self):
        return self._stop.isSet()

但是,如果我运行类似:

st = StoppableThread(target=func)

我得到:

TypeError:__init__()得到了一个意外的关键字参数“目标”

可能是对如何使用它的疏忽。

4

2 回答 2

5

该类StoppableThread不接受或传递任何其他参数到threading.Thread构造函数中。你需要做这样的事情:

class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self,*args,**kwargs):
        super(threading.Thread,self).__init__(*args,**kwargs)
        self._stop = threading.Event()

这会将位置参数和关键字参数都传递给基类。

于 2013-03-17T15:27:55.833 回答
1

您正在覆盖init并且您的init不接受任何参数。您应该添加一个“目标”参数并将其通过 super 传递给您的基类构造函数,甚至更好地允许通过 *args 和 *kwargs 进行任意参数。

IE

def __init__(self,*args,**kwargs):
    super(threading.Thread,self).__init__(*args,**kwargs)
    self._stop = threading.Event()
于 2013-03-17T15:29:34.233 回答