我在python中遇到了一个通用的问题。基类定义一个类属性class_attr
。这个属性是不可变的,在本例中它是一个数字。我想将这个属性从派生类中更改,从而将Base.class_attr
重新绑定到新值(在我的玩具案例中,增加它)。你知道吗
问题是如何做到这一点而不显式地在语句Base.class_attr += 1
中命名Base
。你知道吗
class Base(object):
# class attribute:
class_attr = 0
class Derived(Base):
@classmethod
def increment_class_attr(cls):
Base.class_attr += 1
# is there a solution which does not name the owner of the
# class_attr explicitly?
# This would cause the definition of Derived.class_attr,
# thus Base.class_attr and Derived.class_attr would be
# two independent attributes, no more in sync:
# cls.class_attr += 1
Derived.increment_class_attr()
Derived.increment_class_attr()
print Base.class_attr # 2
请注意:我想问的是一个非常重要的问题,即我是否可以重新绑定父类的属性。我不是在寻找解决这个问题的方法(例如,将increment_class_attr
移到Base)。你知道吗
使用
__bases__
属性:如果您有多重继承:
假设您也不知道继承顺序,则需要为变量测试每个类:
多重继承使用
__mro__
:相关问题 更多 >
编程相关推荐