I need to write a base class (in this example, class A) that will likely, but not always, be subclassed. I want to call the ‘Run’ method from the base class only if its not subclassed, else only call the the ‘Run’ method from the subclasses.
This is what I have, it seems to work but I’m wondering if there is an easier or more Pythonic way.
class A(object):
def __init__(self):
pass
def Run(self):
print "Calling A.Run()"
class B(A):
def __init__(self):
A.__init__(self)
pass
def Run(self):
print "Calling B.Run()"
subs = A.__subclasses__()
if subs: inst = [i() for i in subs]
else: inst = [A()]
[each.Run() for each in inst]
What you have looks correct, except that most programmers would look at the B.Run method and think: “Oh, he forgot to call super. Let me just add that…” but I’m sure you’d explain what you’re doing in your real implementation 🙂
If you’re worried about something like slicing in C++, then be reassured. What you have is good.
As for making it “easier”, I’m not sure how you could simplify it aside from removing A’s empty
__init__function and removingpassfrom B’s__init__.