I’d like to have a child class modify a class variable that it inherits from its parent.
I would like to do something along the lines of:
class Parent(object):
foobar = ["hello"]
class Child(Parent):
# This does not work
foobar = foobar.extend(["world"])
and ideally have:
Child.foobar = ["hello", "world"]
I could do:
class Child(Parent):
def __init__(self):
type(self).foobar.extend(["world"])
but then every time I instantiate an instance of Child, “world” gets appended to the list, which is undesired. I could modify it further to:
class Child(Parent):
def __init__(self):
if type(self).foobar.count("world") < 1:
type(self).foobar.extend(["world"])
but this is still a hack because I must instantiate an instance of Child before it works.
Is there a better way?
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):
Note that this works independently of inheritance, which is probably a good thing.