Inherited class variable modification in Python
Assuming you want to have a separate list in the subclass, not modify the parent class's list (which seems pointless since you could just modify it in place, or put the expected values there to begin with):
class Child(Parent):
foobar = Parent.foobar + ['world']
Note that this works independently of inheritance, which is probably a good thing.
You should not use mutable values in your class variables. Set such values on the instance instead, using the __init__()
instance initializer:
class Parent(object):
def __init__(self):
self.foobar = ['Hello']
class Child(Parent):
def __init__(self):
super(Child, self).__init__()
self.foobar.append('world')
Otherwise what happens in that the foobar
list is shared among not only the instances, but with the subclasses as well.
In any case, you'll have to avoid modifying mutables of parent classes even if you do desire to share state among instances through a mutable class variable; only assignment to a name would create a new variable:
class Parent(object):
foobar = ['Hello']
class Child(Parent):
foobar = Parent.foobar + ['world']
where a new foobar
variable is created for the Child
class. By using assignment, you've created a new list instance and the Parent.foobar
mutable is unaffected.
Do take care with nested mutables in such cases; use the copy
module to create deep copies if necessary.