【发布时间】:2017-07-12 04:09:39
【问题描述】:
这个问题与 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)
问题,是否可以继承命名元组作为 Python 中的基类?是这样,怎么样?
【问题讨论】:
-
这并不完全是您问题的答案,但可能值得一试新的 python dataclasses。在大多数情况下,您将覆盖命名元组,您可能希望使用它们。
标签: python oop inheritance super namedtuple