从父类访问命名元组中的派生属性

时间:2019-05-29 12:28:09

标签: python python-3.x python-2.7 multiple-inheritance namedtuple

我有一个简单的命名元组,它充当了不可变的容器,表征了我设计的类。

从该类(具有namedtuple作为类变量的类)中,派生了多个子类,它们都覆盖了此属性,并向命名元组添加新字段

我想保留在父类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

我将丢失在中间类中添加的所有信息。

0 个答案:

没有答案