我在谷歌上搜索和玩了一段时间,但没有结果尝试这样做:
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
简而言之,我希望能够“使用并重写”父类中的类属性。你知道吗
引用父类属性并连接到它:
类主体的执行非常类似于函数,局部名称构成类属性。
cl_att
在为B
和C
创建主体的新“function”中不存在,因此需要直接引用基类上的属性。你知道吗演示:
假设只有一个父类,可以使用在子类的答案末尾定义的
inherit_and_append
装饰器来获得所需的结果,如下所示:如果有更高级的要求或条件,可以进一步扩展decorator。你知道吗
相关问题 更多 >
编程相关推荐