超类__init__不识别它的kwargs

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__() got an unexpected keyword argument 'target' ```
很可能是关于如何使用它的疏忽导致的。
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()

这将同时传递位置参数和关键字参数到基类。

1
你正在覆盖 init 方法,但是你的 init 方法没有任何参数。你应该添加一个 "target" 参数,并通过 super 将其传递到基类构造函数中,或者更好地通过 *args 和 *kwargs 允许任意参数。
def __init__(self,*args,**kwargs):
    super(threading.Thread,self).__init__(*args,**kwargs)
    self._stop = threading.Event()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接