Python类属性和子类

时间:2015-05-22 14:48:45

标签: python class subclassing

我用谷歌搜索并播放了一段时间,但没有结果试图做这样的事情:

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

简而言之,我希望能够“使用然后覆盖”来自父类的类属性。

2 个答案:

答案 0 :(得分:7)

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

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创建实体,因此您需要直接在基类上引用该属性。

演示:

>>> 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'

答案 1 :(得分:1)

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

php 5.3.28

如果有更高级的要求或条件,您可以进一步扩展装饰器。

inherit_and_append