这个问题与Inherit namedtuple from a base class in python相反,目的是从名称元组继承子类,而不是从名称继承子类。
在正常继承中,这样做是有效的:
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输出
>>> 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输出
>>> Z(1,2,3,4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __new__() takes exactly 4 arguments (5 given)问题是,是否可以继承namedtuple作为Python中的一个基类?如果是,怎么做?
发布于 2017-02-22 08:24:26
您可以,但您必须重写__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]发布于 2017-07-19 14:30:42
我认为您可以通过将所有字段包含在原始命名元组中,然后像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)发布于 2019-05-05 07:06:37
就在两年后,我就带着同样的问题来到这里。
我个人认为@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)
# 6https://stackoverflow.com/questions/42385916
复制相似问题