0

I am confused about overriding. When we define a init method inside a class, is it really overriding the init method of the base "object" class?. As far as i know, The basic rule of overriding a method is that both overriding and overriden method should have the same signature. But in the example below, if we check the signatures of the init method of the object class and child class, its not equal.

from inspect import signature
class Child:
    def __init__(self, age):
        self.age = age
print(signature(Child.__init__) == object.__init__)
Random Davis
  • 6,662
  • 4
  • 14
  • 24
ram
  • 11
  • 1
  • 1
    Does this answer your question? [Python Method overriding, does signature matter?](https://stackoverflow.com/questions/6034662/python-method-overriding-does-signature-matter) – JonSG Apr 12 '23 at 19:47
  • Not exactly the same question, but the answers here are the answers to your question: [Mypy accepts an incompatible type in __init__ override](https://stackoverflow.com/q/69394820/12299000) – kaya3 Apr 12 '23 at 19:54
  • In a statically typed world, you are correct: the type of the override should be a subtype of the function being overriden. Python is *not* statically typed, though, and the signature of `object.__init__` long predates the addition of type hints to the language. Ideally, `object.__init__` might accept, but *ignore*, any arguments it receives. – chepner Apr 12 '23 at 20:04
  • Other concerns aside, `signature(Child.__init__) == object.__init__` doesn't actually compare the signatures. – user2357112 Apr 12 '23 at 20:07

1 Answers1

0

When you define an __init__ method, you instruct Python how to instantiate the class. So you are overriding the __init__ method of the base object class because now to instantiate a new object of class Child you will have to use your new __init__ method.

In Python, the functions overridden in the subclasses don't need to have the same signatures as the functions in the parent class, as long as they respect the Liskov Substitution Principle. This is not necessary for constructors though.

TheOneMusic
  • 1,776
  • 3
  • 15
  • 39