Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect method overloading in subclasses in python?

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?

like image 625
Brian Avatar asked Feb 24 '12 19:02

Brian


People also ask

Can we overload a method in subclass?

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.

Does overloading work with inheritance in Python?

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.

How do you stop a method overriding in Python?

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".

How do you override a subclass in Python?

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.


1 Answers

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 
like image 200
wberry Avatar answered Sep 21 '22 08:09

wberry