此问题与Inherit namedtuple from a base class in python相反,目的是从namedtuple继承子类,反之亦然。
在正常继承中,此方法有效:
class Y(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
class Z(Y):
def __init__(self, a, b, c, d):
super(Z, self).__init__(a, b, c)
self.d = d
[out]:
>>> Z(1,2,3,4)
<__main__.Z object at 0x10fcad950>
但是如果基类是namedtuple
:
from collections import namedtuple
X = namedtuple('X', 'a b c')
class Z(X):
def __init__(self, a, b, c, d):
super(Z, self).__init__(a, b, c)
self.d = d
[out]:
>>> Z(1,2,3,4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __new__() takes exactly 4 arguments (5 given)
问题,是否可以在Python中继承namedtuple作为基类?是这样吗?
您可以,但是您必须重写__new__
,在__init__
之前隐式调用它:
class Z(X):
def __new__(cls, a, b, c, d):
self = super(Z, cls).__new__(cls, a, b, c)
self.d = d
return self
>>> z = Z(1, 2, 3, 4)
>>> z
Z(a=1, b=2, c=3)
>>> z.d
4
但是d
只是一个独立的属性!
>>> list(z)
[1, 2, 3]
我认为您可以通过包含所有字段来实现您想要的在原始的命名元组中,然后调整参数数量如上文schwobaseggl所述,使用__new__
。例如,解决max的情况,其中一些输入值将被计算不是直接提供,而是以下作品:
from collections import namedtuple
class A(namedtuple('A', 'a b c computed_value')):
def __new__(cls, a, b, c):
computed_value = (a + b + c)
return super(A, cls).__new__(cls, a, b, c, computed_value)
>>> A(1,2,3)
A(a=1, b=2, c=3, computed_value=6)
两年后,我来到这里时遇到了完全相同的问题。我个人认为@property
装饰器会更好地适合这里:
from collections import namedtuple
class Base:
@property
def computed_value(self):
return self.a + self.b + self.c
# inherits from Base
class A(Base, namedtuple('A', 'a b c')):
pass
cls = A(1, 2, 3)
print(cls.computed_value)
# 6