Reinitialize parent class attributes during child class definition

五迷三道 提交于 2021-01-28 15:44:28

问题


I'm using class attributes as a neat way to keep common strings used throughout my project. Parent class has an 'main' attribute that is used to compose other attributes.

Some of use cases need to use child class with this 'main' attribute changed. How can I force the child class to run the parent class attributes initialization for not-overridden attributes?

Basically, I want this code to work:

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


class Two(One):
    MAIN_ATTR = 'two'

assert Two.COMPOSED_ATTR == 'two composed'

回答1:


You can use metaclass to construct attributes of both parent and child classes:

#!/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'


来源:https://stackoverflow.com/questions/54783775/reinitialize-parent-class-attributes-during-child-class-definition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!