我有一个简单的命名元组,它作为一个不可变容器来描述我设计的一个类。
从这个类(将命名元组作为类变量),我派生了多个子类,它们都覆盖了这个属性并将新字段添加到命名元组
我想保留在父类 ID 中定义的字段,只添加新的字段。我假设您可以简单地将旧 ID 保留在类中并执行类似 ID.2nd = " added form child" 但如果您可以简单地覆盖 ID 变量并通过调用 super 访问先前定义的 ID,我会更喜欢() 或者其他的东西
from collections import namedtuple
ID = namedtuple("myTuple", ["first", "second", "third", "fourth"])
ID.__new__.__defaults__ = ("default from parentclass", None , None , None)
class Parent(object):
_ID = ID()
def __init__(self, arg):
self.arg = arg
class Child(Parent):
#if there is a new _ID defined in Child
#, keep the fields it adds but also add the
#ones from the parent:
_ID = ID(second="adding from child")
#it should now contain the fields _ID.first == "default from parent" from parentclass
#and _ID.second == "adding from child"
到目前为止,这是可行的,但是如果我现在有另一个孩子
class Child2(Child):
_ID = ID(third="adding from child")
#and now something like _ID.second = super()._ID.second
我将丢失在中间类中添加的所有信息。