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__()予期しないキーワード引数'target'を取得しました

おそらく、これをどのように使用すべきかについての見落としです。

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は引数を取りません。「target」引数を追加し、それをsuperを使用して基本クラスのコンストラクターに渡すか、*argsおよび*kwargsを介して任意の引数を許可する必要があります。

つまり

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