超类 __init__ 无法识别其 kwargs

4 投票
2 回答
1541 浏览
提问于 2025-04-17 19:24

我正在尝试使用 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)

我得到的错误是:

类型错误:__init__() 收到了一个意外的关键字参数 'target'

这可能是对如何使用这个类的一个疏忽。

2 个回答

1

你在重写init方法,但你的init方法没有接收任何参数。你应该添加一个“target”参数,并通过super把它传递给父类的构造函数。更好的做法是使用*args和**kwargs来允许接收任意参数。

也就是说:

def __init__(self,*args,**kwargs):
    super(threading.Thread,self).__init__(*args,**kwargs)
    self._stop = threading.Event()
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()

这样可以把位置参数和关键字参数都传递给父类。

撰写回答