以下代码失败
from collections import namedtuple
import pickle
class Foo(namedtuple("_Foo", ["a", "b"])):
def __new__(cls, **kwargs):
self = super().__new__(cls, **kwargs)
# some custom code
return self
foo = Foo(a=1, b=2)
pickle.loads(pickle.dumps(foo))
使用
Traceback (most recent call last):
File "bar.py", line 10, in <module>
pickle.loads(pickle.dumps(foo))
TypeError: __new__() takes 1 positional argument but 3 were given
如果我删除了新的__new__
实现,它可以工作,但是我想在那里有一些自定义代码。我该如何更改__new__
的实现以免出现错误?
我正在运行Python 3.5。
答案 0 :(得分:2)
原因很简单;通常,C API将内容作为位置参数而不是命名参数传递。因此,您只需要为此提供*args
:
from collections import namedtuple
import pickle
class Foo(namedtuple("_Foo", ["a", "b"])):
def __new__(cls, *args, **kwargs):
self = super().__new__(cls, *args, **kwargs)
# some custom code
return self
foo = Foo(a=1, b=2)
pickle.loads(pickle.dumps(foo))