Rio mario
Rio mario

Reputation: 283

Is this a constructor or a method

Is __init__ in python a constructor or a method?

Somewhere it says constructor and somewhere it says method, which is quite confusing.

Upvotes: 1

Views: 103

Answers (2)

Vidhya G
Vidhya G

Reputation: 2320

In addition to the answer by @wim it is worth noting that the object has already been created by the time __init__ is called i.e. __init__ is not a constructor. Furthermore, __init__ methods are optional: you do not have to define one. Finally, an __init__ method is defined first only by convention i.e. it could be defined after any of the other methods.

Upvotes: 0

wim
wim

Reputation: 362857

It is correct to call it a method. It is incorrect, or at best inaccurate, to call it a constructor.

Specifically, it is a magic method. They are also called special methods, "dunders", and a few other names.

This particular method is used to define the initialisation behavior of an object. It is not really similar to a constructor, and it is not even the first method to be called on a new instance.

We use __init__ to set up the state of an already-created instance. It will be automatically called when we use the syntax A() to create an instance of a class A, which is why someone might loosely refer to it as a "constructor". But the responsibility of __init__ is not related to instance construction, really the __new__ magic method is more similar to a constructor in that respect.

Upvotes: 6

Related Questions