从 namedtuple 基类继承

新手上路,请多包涵

这个问题问的是 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 许可协议

阅读 1.1k
2 个回答

你可以,但你必须覆盖 __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]

原文由 user2390182 发布,翻译遵循 CC BY-SA 3.0 许可协议

我认为您可以通过在原始命名元组中包含所有字段,然后使用 __new__ 调整参数数量来实现您想要的效果,正如上面 schwobaseggl 所建议的那样。例如,为了解决 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)

原文由 TimH 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题