Python Method overriding, does signature matter? Python Method overriding, does signature matter? python python

Python Method overriding, does signature matter?


In Python, methods are just key-value pairs in the dictionary attached to the class. When you are deriving a class from a base class, you are essentially saying that method name will be looked into first derived class dictionary and then in the base class dictionary. In order to "override" a method, you simply re-declare the method in the derived class.

So, what if you change the signature of the overridden method in the derived class? Everything works correctly if the call is on the derived instance but if you make the call on the base instance, you will get an error because the base class uses a different signature for that same method name.

There are however frequent scenarios where you want derived class method have additional parameters and you want method call work without error on base as well. This is called "Liskov substitution principle" (or LSP) which guarantees that if person switches from base to derived instance or vice versa, they don't have to revamp their code. To do this in Python, you need to design your base class with the following technique:

class Base:    # simply allow additional args in base class    def hello(self, name, *args, **kwargs):        print("Hello", name)class Derived(Base):      # derived class also has unused optional args so people can      # derive new class from this class as well while maintaining LSP      def hello(self, name, age=None, *args, **kwargs):          super(Derived, self).hello(name, age, *args, **kwargs)           print('Your age is ', age)b = Base()d = Derived()b.hello('Alice')        # works on base, without additional paramsb.hello('Bob', age=24)  # works on base, with additional paramsd.hello('Rick')         # works on derived, without additional paramsd.hello('John', age=30) # works on derived, with additional params

Above will print:

    Hello Alice    Hello Bob    Hello Rick    Your age is  None    Hello John    Your age is  30
.Play with this code


Python will allow this, but if method1() is intended to be executed from external code then you may want to reconsider this, as it violates LSP and so won't always work properly.


In python, all class methods are "virtual" (in terms of C++). So, in the case of your code, if you'd like to call method1() in super class, it has to be:

class Super():    def method1(self):        passclass Sub(Super):    def method1(self, param1, param2, param3):       super(Sub, self).method1() # a proxy object, see http://docs.python.org/library/functions.html#super       pass

And the method signature does matter. You can't call a method like this:

sub = Sub()sub.method1()