r/Python • u/declspecl • 3d ago
Discussion Constructors: __init__, __new__, both, neither?
Hi all, I'm doing some research on what programmers believe is the class constructor in Python. I made a poll here: https://strawpoll.com/05ZdzVzdmn6 and would appreciate all responses, thanks!
0
Upvotes
6
u/droooze 3d ago
"Class constructor" is terminology which refers to something concrete in C++ and Java. In those languages, it
is a method with the same name as the class which is invoked with the call syntax (for a
class Point
, this isPoint()
);allows customisation ("initialisation") of an already-created instance;
must not return anything.
__init__
does (2) and (3). (1) is enabled by the metaclass's__call__
method, but unlike the other languages it must also handle allocation (instance creation, normally by calling a class's__new__
method internally), and the returned result must be a fully-initialised object.Nothing in Python corresponds to "the class constructor" in other languages;
__init__
comes the closest, but is also optional, as you can do class construction in metaclass__call__
or class__new__
as well. However, if you don't do class construction in__init__
, Python forces you to handle allocation (instance creation) and instance customisation together.