将** kwargs错误线程化并传递给TypeError

时间:2013-02-25 12:52:12

标签: python multithreading class dictionary kwargs

我对Python很陌生,并且正在考虑通过这篇文章为某些代码使用线程: Python - Using threads or a queue to iterate over a for loop that calls a function

我想知道为什么这个简单的示例代码出错

Error: line 1: TypeError: file <maya console> line 4: __init__() got
an unexpected keyword argument 'A' #

我的代码:

import threading
class Test(threading.Thread):
    def __init__(self, **kwargs):
        super(Test, self).__init__( **kwargs)
        self.__dict__.update(**kwargs)

A = None
B = 1   
test = Test(A = A, B = B)
print test.A
print test.B

我的假设是它与super(Test, self).__init__( **kwargs)调用有关,但我不确定如何解决它。我的目标是传递相当多的论据,这就是我开始使用**kwargs的原因。

2 个答案:

答案 0 :(得分:2)

您将参数A和B传递给Thread构造函数,而不需要它们。可能你应该只调用没有参数的超级构造函数。

答案 1 :(得分:0)

threading.Thread.__init__预计(最多)grouptargetnameargskwargsverbose关键字参数

由于您有大量额外参数(可能超过threading.Thread.__init__期望的六个参数), 明确提取这六个并用

处理其余部分可能不那么重要
self.__dict__.update(**kwargs)

import threading

class Test(threading.Thread):
    def __init__(self, **kwargs):
        super(Test, self).__init__(
            **{k: v for k in 'group target name args kwargs verbose'.split()
               if k in kwargs})
        self.__dict__.update(**kwargs)

A = None
B = 1
test = Test(A=A, B=B)
print test.A
print test.B

注意,如果您在没有参数的情况下致电__init__

super(Test, self).__init__()

然后threading.Thread使用的一大堆属性将不会被设置:

class Thread(_Verbose):    
    def __init__(self, group=None, target=None, name=None,
                 args=(), kwargs=None, verbose=None):
        assert group is None, "group argument must be None for now"
        _Verbose.__init__(self, verbose)
        if kwargs is None:
            kwargs = {}
        self.__target = target
        self.__name = str(name or _newname())
        self.__args = args
        self.__kwargs = kwargs
        self.__daemonic = self._set_daemon()
        self.__ident = None
        self.__started = Event()
        self.__stopped = False
        self.__block = Condition(Lock())
        self.__initialized = True
        # sys.stderr is not stored in the class like
        # sys.exc_info since it can be changed between instances
        self.__stderr = _sys.stderr

我认为这不是你想要发生的......