r/Python 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

22 comments sorted by

View all comments

6

u/droooze 3d ago

"Class constructor" is terminology which refers to something concrete in C++ and Java. In those languages, it

  1. is a method with the same name as the class which is invoked with the call syntax (for a class Point, this is Point());

  2. allows customisation ("initialisation") of an already-created instance;

  3. 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.