【发布时间】:2019-06-12 13:32:24
【问题描述】:
我想知道是否可以防止父类变量的更改被继承自父类的子类采用。
我会有类似的东西:
class Parent(object):
foo = 'bar'
class Child(Parent):
pass
覆盖Parent.foo 也会导致Child.foo 发生变化:
>>> Parent.foo = 'rab'
>>> print Parent.foo
rab
>>> print Child.foo
rab
有没有办法防止这种情况发生,或者我不应该这样做?
解决方案
阅读@quamrana 的回答,我意识到可以使用元类来防止这种情况:
class Meta(type):
def __new__(cls, new, bases, dct):
dct['foo'] = 'bar'
return super(Meta, cls).__new__(cls, new, bases, dct)
class Parent(object):
__metaclass__ = Meta
class Child(Parent):
pass
>>> Parent.foo = 'rab'
>>> print Parent.foo
rab
>>> print Child.foo
bar
【问题讨论】:
标签: python python-2.7 inheritance class-variables