I was wondering whether it is possible to prevent changes to a Parent class-variable to be adopted by a Child class that inherits from the Parent class.
I would have something like:
class Parent(object):
foo = 'bar'
class Child(Parent):
pass
Overwriting Parent.foo
will also cause Child.foo
to change:
>>> Parent.foo = 'rab'
>>> print Parent.foo
rab
>>> print Child.foo
rab
Is there a way to prevent this or should I not be wanting this?
Solution
Reading @quamrana 's answer, I realised this could be prevented using a metaclass:
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
This behaviour occurs since foo
is the same variable in both classes.
This is analogous to a global variable in a module and being able to see that two different functions in that module can both see and change that global.
A possible fix is this:
class Parent(object):
foo = 'bar'
class Child(Parent):
foo = Parent.foo
Parent.foo = 'zoo'
print(Child.foo)
Output:
bar
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.