这个问题问的是 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
[出去]:
>>> 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)
问题是, 是否可以在 Python 中将 namedtuples 作为基类继承?如果是这样,如何?
原文由 alvas 发布,翻译遵循 CC BY-SA 4.0 许可协议
你可以,但你必须覆盖
__new__
之前隐式调用__init__
:但是
d
将只是一个独立的属性!