覆盖“ __new__”时,Pickle对从“ namedtuple”继承的类不起作用

时间:2019-06-20 01:34:33

标签: python python-3.x python-3.5 pickle namedtuple

以下代码失败

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。

1 个答案:

答案 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))