0

I read on Google that for method overriding in python the methods in the base and derive class should have same name and same parameters. Is it true? Can parameters be different? See my code below:

class A:
    def add(self,a,b):
        return a+b
class B(A):
    def add(self,a,b,c): 
        return a+b+c

Can we still call it overriding? because parameters of both methods are different and I read on Google for method overriding, two methods name and parameters should be same. Please clear my confusion.

Thanks

azro
  • 53,056
  • 7
  • 34
  • 70
  • They *can* be different - the child class implementation hides the base class implementation. However it's generally not a very good idea to change function signatures in the child class because it violates [certain](https://en.wikipedia.org/wiki/Liskov_substitution_principle) [best practices](https://en.wikipedia.org/wiki/SOLID) for object-oriented design. – 0x5453 Aug 25 '22 at 17:46
  • @0x5453 Can you explain a bit...They can be different? How? –  Aug 25 '22 at 17:52
  • I mean that the parameters are *allowed* to be different. i.e. your example is valid python. But because the parameters are different, it may behave unexpectedly in certain situations. – 0x5453 Aug 25 '22 at 18:02
  • @0x5453 there are certain scenarios where we have to add one or two additional parameters to the method (overriding the method of base class)of child class to extend it's functionality. How can we handle that? –  Aug 25 '22 at 19:02
  • # How to handle such cases """class Employee: def __init__(self,name,age,pay): self.name=name self.age=age self.pay=pay class Developer: def __init__(self,name,age,pay,programming_lang): super().__init__(name,age,pay) self.programming_lang=programming_lang""" #Overriding the __init__ method of base class(Adding one more parameter programming_lang) –  Aug 25 '22 at 19:06
  • Normally, you should not add parameters to method overrides in child classes because it violates the Liskov Substitution Principle, i.e. it makes it so that code that calls that method must know the concrete type of the object, which defeats the whole point of polymorphism. **However**, `__init__` is special - it is not meant to be used polymorphically, so it is completely fine to add parameters in child classes. Generally, best practice is to call `super().__init__(...)` and "forward" all of the arguments that the base class constructor requires. TL;DR: Your `Developer` example is fine. – 0x5453 Aug 25 '22 at 19:25

1 Answers1

0

Yes, it can still be called overriding. Parameters can be optional, too.

edit: See https://stackoverflow.com/a/54155637/7415199

Johannes Heuel
  • 156
  • 2
  • 4