2

Python will resolve a method name in the class of the method and all parent classes of that class until it resolves.

Does this apply to the constructor as well. I.e., if a class does not define __init__() but its parent does, will the parent constructor automatically be called?

Terrence Brannon
  • 4,760
  • 7
  • 42
  • 61
  • What happened when you tried it? – kindall Jul 11 '13 at 15:21
  • Quibble: `__init__` is not a constructor. It's a normal instance method that is called immediately on instantiation. – Daniel Roseman Jul 11 '13 at 15:21
  • 1
    @DanielRoseman If `__init__` isn't a constructor, then the things called constructors in virtually every other class-based OO language (at the very least: C++, C#, Java) aren't constructors either. Those too are called on the new object after immediately it is constructed. `__new__` doesn't really have an analogue in most of those languages, you'd have to emulate it and would end up with a factory. –  Jul 11 '13 at 15:41

1 Answers1

7

The short answer is: yes. This is how inheritance works.

This is also the reason why you should call the parent constructor explicitly most of the time (unless you want to do otherwise for some reason), when you are overriding method within child class.

It is also worth learning about Method Resolution Order in Python: Method Resolution Order (MRO) in new style Python classes. It defines the order with which the methods are resolved (especially important in case of multiple inheritance).

Community
  • 1
  • 1
Tadeck
  • 132,510
  • 28
  • 152
  • 198