当覆盖“__new__”时,Pickle 不适用于从 "namedtuple" 继承的 class

Pickle doesn't work for class inherited from "namedtuple" when overriding "__new__"

以下代码失败

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.

原因很简单;通常,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))