类的所有子类中的字段

时间:2016-06-19 13:54:18

标签: python inheritance

我们假设我们有一个班级A,一个班级B,其继承自A和班级CD和{{ 1}}继承自E

我们希望所有这些类都使用默认值初始化属性B,并且我们希望该属性是可变的,并且对于每个类的实例都有一个单独的值,即它不应该是所有子类使用的_f的静态常量值。

执行此操作的一种方法是在A {'1}}方法中定义A,然后在子类中依赖此方法:

_f

有没有什么好的Pythonic方法可以避免这种情况,并且可能避免使用元类?

1 个答案:

答案 0 :(得分:0)

如果您的目标是通过消除调用基类构造函数来简化子类构造函数,但仍然能够覆盖子类中的默认值,那么有一个共同的范例可以利用Python将返回类的值的事实如果实例上不存在该属性。

使用稍微更具体的例子,而不是......

class Human(object):

    def __init__(self):
        self._fingers = 10

    def __repr__(self):
        return 'I am a %s with %d fingers' % (self.__class__.__name__, self._fingers)


class MutatedHuman(Human):

    def __init__(self, fingers):
        super(MutatedHuman, self).__init__()
        self._fingers = fingers


print MutatedHuman(fingers=11)
print Human()

......你可以使用......

class Human(object):

    _fingers = 10

    def __repr__(self):
        return 'I am a %s with %d fingers' % (self.__class__.__name__, self._fingers)


class MutatedHuman(Human):

    def __init__(self, fingers):
        self._fingers = fingers


print MutatedHuman(fingers=11)
print Human()

......两者都输出......

I am a MutatedHuman with 11 fingers
I am a Human with 10 fingers

重要的一点是,第二个示例中的行self._fingers = fingers不会覆盖类Human上设置的默认值,而只是在引用为self._fingers时隐藏它。

当变量引用可变类型(例如列表)时,它有点毛茸茸。您必须小心不要对默认值执行操作,这将对其进行修改,尽管执行self.name = value仍然是安全的。

这种方法的优点是,与其他方法相比,它往往导致更少的代码行,这通常是一件好事(tm)。