在子类定义期间重新初始化父类属性

时间:2019-02-20 10:12:10

标签: python python-3.x inheritance

我将类属性用作一种整齐的方式,以在整个项目中使用通用字符串。父类具有一个“ main”属性,该属性用于组成其他属性。

某些用例需要使用子类,并且此“ main”属性已更改。如何强制子类为未覆盖的属性运行父类属性初始化?

基本上,我希望这段代码能正常工作:

class One:
    MAIN_ATTR = 'one'
    COMPOSED_ATTR = ' '.join([MAIN_ATTR, 'composed'])


class Two(One):
    MAIN_ATTR = 'two'

assert Two.COMPOSED_ATTR == 'two composed'

1 个答案:

答案 0 :(得分:1)

您可以使用元类构造父级和子级的属性:

#!/usr/bin/python3.6


class Composer(type):
    def __new__(cls, name, bases, attrs):
        attrs['COMPOSED_ATTR'] = ' '.join([attrs['MAIN_ATTR'], 'composed'])
        return super(Composer, cls).__new__(cls, name, bases, attrs)


class One(metaclass=Composer):
    MAIN_ATTR = 'one'


class Two(One):
    MAIN_ATTR = 'two'


assert Two.COMPOSED_ATTR == 'two composed'