Python类属性和子类化

2024-10-02 22:25:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我在谷歌上搜索和玩了一段时间,但没有结果尝试这样做:

class  A(object):
    cl_att = 'I am an A class attribute'

class  B(A):
    cl_att += ' modified for B type'

class  C(A):
    cl_att += ' modified for C type'


instA = A()
print insAt.cl_att
>>> I am an A class attribute

instB = B()
print instB.cl_att
>>> I am an A class attribute modified for B type

instC = C()
print instC.cl_att
>>> I am an A class attribute modified for C type

print instA.cl_att
>>> I am an A class attribute

简而言之,我希望能够“使用并重写”父类中的类属性。你知道吗


Tags: anforobjectcltypeattributeamatt
2条回答

引用父类属性并连接到它:

class  A(object):
    cl_att = 'I am an A class attribute'

class  B(A):
    cl_att = A.cl_att + ' modified for B type'

class  C(A):
    cl_att = A.cl_att + ' modified for C type'

类主体的执行非常类似于函数,局部名称构成类属性。cl_att在为BC创建主体的新“function”中不存在,因此需要直接引用基类上的属性。你知道吗

演示:

>>> class  A(object):
...     cl_att = 'I am an A class attribute'
... 
>>> class  B(A):
...     cl_att = A.cl_att + ' modified for B type'
... 
>>> class  C(A):
...     cl_att = A.cl_att + ' modified for C type'
... 
>>> A.cl_att
'I am an A class attribute'
>>> B.cl_att
'I am an A class attribute modified for B type'
>>> C.cl_att
'I am an A class attribute modified for C type'

假设只有一个父类,可以使用在子类的答案末尾定义的inherit_and_append装饰器来获得所需的结果,如下所示:

class  A(object):
    cl_att = 'I am an A class attribute'

@inherit_and_append('cl_att')
class  B(A):
    cl_att = ' modified for B type'

@inherit_and_append('cl_att')
class  C(A):
    cl_att = ' modified for C type'

如果有更高级的要求或条件,可以进一步扩展decorator。你知道吗

class inherit_and_append(object):
    def __init__(self, *attrs):
        super(inherit_and_append, self).__init__()

        self._attrs = attrs

    def __call__(self, klass):
        parent = klass.__bases__[0]  # Assuming you have a single parent class
        for attr in self._attrs:
            if not hasattr(parent, attr):
                raise AttributeError("'{}' class has no '{}' attribute".format(parent.__name__, attr))

            parent_value = getattr(parent, attr)
            klass_value = getattr(klass, attr)
            setattr(klass, attr, parent_value + klass_value)

        return klass

相关问题 更多 >