I have a class that is a super-class to many other classes. I would like to know (in the __init__()
of my super-class) if the subclass has overridden a specific method.
I tried to accomplish this with a class method, but the results were wrong:
class Super: def __init__(self): if self.method == Super.method: print 'same' else: print 'different' @classmethod def method(cls): pass class Sub1(Super): def method(self): print 'hi' class Sub2(Super): pass Super() # should be same Sub1() # should be different Sub2() # should be same >>> same >>> different >>> different
Is there any way for a super-class to know if a sub-class has overridden a method?
Note: In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass instance methods—they are new methods, unique to the subclass.
This code doesn't make a call to the version of add() that takes in two arguments to add. So we find it safe to say Python doesn't support method overloading.
To enforce safe module design, I want to prevent run() from being overridden. Solve my problem in a Pythonic way :) (In Java, I'd just declare run() as final in the superclass, and declare runBody as abstract.) @Will In the docstring for run , write: "Don't override this, override runBody".
In Python method overriding occurs by simply defining in the child class a method with the same name of a method in the parent class. When you define a method in the object you make this latter able to satisfy that method call, so the implementations of its ancestors do not come in play.
You can use your own decorator. But this is a trick and will only work on classes where you control the implementation.
def override(method): method.is_overridden = True return method class Super: def __init__(self): if hasattr(self.method, 'is_overridden'): print 'different' else: print 'same' @classmethod def method(cls): pass class Sub1(Super): @override def method(self): print 'hi' class Sub2(Super): pass Super() # should be same Sub1() # should be different Sub2() # should be same >>> same >>> different >>> same
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With