Say I have this class:
class FooClass(object):
foos = ["foo", "bar"]
def do_foos(self):
for foo in self.foos:
print("I have a " + foo)
# ...
I want to create a SpecialisedFooClass for this class which extends FooClass
, adding an item "spec"
to foos
(i.e. so that foos
contains ["foo", "bar", "spec"]
).
SpecialisedFooClass.foos
should depend on FooClass.foos
: If I change FooClass
' definition so that foos
contains ["foo", "bam", "bat"]
, SpecialisedFooClass.foos
should then contain ["foo", "bam", "bat", "spec"]
.
This is the best way I've come up with so far:
class SpecialisedFooClass(FooClass):
foos = FooClass.foos + ["spec"]
But I find the explicit reference to FooClass
concerning. When I decide to add an intermediary subclass (i.e. when SpecialisedFooClass
' superclass changes) I will inevitably forget to update this reference. I have in fact already made this mistake IRL with the codebase I'm working on (which doesn't actually deal with foos, bams, and bats...).
There's actually no special requirement in my case that foos
is a class member rather than an instance member, so this would also work, but I find it ugly. Also, the super
call still has an explicit class reference - less worrying here because its to the class it appears in, though.
class FooClass(object):
def __init__(self, *args, **kwargs):
self.foos = ["foo", "bar"]
def do_foos(self):
for foo in self.foos:
print("I have a " + foo)
class SpecialisedFooClass(FooClass):
def __init__(self, *args, **kwargs):
super(SpecialisedFooClass, self).__init__(*args, **kwargs)
self.foos.append("spec")
What other options exist, and is there a "Pythonic" way to do this?