开发者

Only calling base class if its not subclassed in Python

开发者 https://www.devze.com 2023-03-13 12:18 出处:网络
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

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


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")
0

精彩评论

暂无评论...
验证码 换一张
取 消