tMC
tMC

Reputation: 19325

Only calling base class if its not subclassed in Python

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]

Upvotes: 0

Views: 88

Answers (2)

idbrii
idbrii

Reputation: 11916

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 removing pass from B's __init__.

Upvotes: 1

Bastien Léonard
Bastien Léonard

Reputation: 61703

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 happens by default, the most specific method is called.

If you really don't want the base method to be available from subclasses, you can write something like this:

class C(object):
    def Run(self):
        if self.__class__ != C:
            raise NotImplementedError("You need to override this method")

Upvotes: 1

Related Questions