我似乎无法实例化一个 namedtuple
子类:
from collections import namedtuple
foo = namedtuple("foo",["a","b","c"])
class Foo(foo):
def __init__(self, a, b):
super(Foo, self).__init__(a=a,b=b,c=a+b)
当我尝试创建一个实例时,我得到:
>>> Foo(1,2)
TypeError: __new__() takes exactly 4 arguments (3 given)
我期望 Foo(1,2,3)
。
似乎有一个解决方法:使用类方法代替 __init__
:
class Foo(foo):
@classmethod
def get(cls, a, b):
return cls(a=a, b=b, c=a+b)
现在 Foo.get(1,2)
确实返回了 foo(a=1, b=2, c=3)
。
但是,这看起来很难看。
这是唯一的方法吗?
最佳答案
命名元组不可变,您需要使用__new__
method相反:
class Foo(foo):
def __new__(cls, a, b):
return super(Foo, cls).__new__(cls, a=a, b=b, c=a+b)
(注意:__new__
隐含地成为一个静态方法,因此您需要显式传递 cls
参数;该方法返回新创建的实例)。
__init__
无法使用,因为它是在实例创建之后调用的,因此无法再改变元组。
请注意,您确实应该向子类添加 __slots__ = ()
行;一个命名的元组没有 __dict__
字典使你的内存困惑,但你的子类会除非你添加 __slots__
行:
class Foo(foo):
__slots__ = ()
def __new__(cls, a, b):
return super(Foo, cls).__new__(cls, a=a, b=b, c=a+b)
这样您就可以将命名元组的内存占用保持在较低水平。查看__slots__
文档:
The action of a
__slots__
declaration is limited to the class where it is defined. As a result, subclasses will have a__dict__
unless they also define__slots__
(which must only contain names of any additional slots).
关于python - 无法创建 namedtuple 子类的实例 : TypeError: __new__() takes exactly 4 arguments (3 given),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48529355/