1

I have this small example with parent/child classes. I know the code will run without problem, but is it a good practice to override a parent's method with a method which has a different signature? PyCharm does not seem to think it is a good idea:

Signature of method 'Daughter.do()' does not match signature of base method in class 'Mother'

For information, calling Parent method do should execute do(self) not do(self, c).

Code example:

class Parent:

    def __init__(self):
        self._a = "a"

    def do(self):
        print("Parent: {}".format(self._a))


class Child(Parent):

    def __init__(self):
        Parent.__init__(self)
        self._b = "b"

    def do(self, c):
        print("Child: {}".format(self._a))
        print("Child: {}".format(self._b))
        print("Child: {}".format(c))
balderman
  • 22,927
  • 7
  • 34
  • 52
Berthier
  • 36
  • 6

1 Answers1

1

It is a bad practice. It for example breaks Liskov substitution principle; If you have a function, that expects a Mother instance, and calls do() on it, it will fail when you pass a Daughter to it.

See this example:

def call_do(mother: Mother) -> None:
     mother.do()

You should be able to pass an instance of Mother, or an instance of any of its subclasses into call_do.

But if you now do:

daughter = Daughter()
call_do(daughter)

you will get a TypeError.

ruohola
  • 21,987
  • 6
  • 62
  • 97