问题
I'm pretty new to Python and was looking into using threading for some code via this post: Python - Using threads or a queue to iterate over a for loop that calls a function
I was wondering why this simple example code errors out to
Error: line 1: TypeError: file <maya console> line 4: __init__() got
an unexpected keyword argument 'A' #
My code:
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
My assumption is it has to do with super(Test, self).__init__( **kwargs)
call, but I'm not sure how to work around it. My goal is pass in a rather large amount of arguments which is why I'm using **kwargs
to begin with.
回答1:
threading.Thread.__init__
expects (at most) group
, target
, name
, args
, kwargs
and verbose
keyword arguments.
Since you have a large number of extra arguments (presumably more than the six that threading.Thread.__init__
expects), then
it may be less work to explicity extract those six and handle the rest with
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
Note, if you call __init__
with no arguments:
super(Test, self).__init__()
then a whole bunch of attributes used by threading.Thread
will not be set:
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
I don't think that is what you want to happen...
回答2:
You're passing the arguments A and B to the Thread constructor, which doesn't need them. Probably you should just call the super constructor with no arguments.
来源:https://stackoverflow.com/questions/15067421/threading-and-passing-values-with-kwargs-errors-to-typeerror