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

11

u/bubudumbdumb 3d ago

/s ?

9

u/ntropia64 3d ago

I am not sure this is up for debate. The __new__ method gets called before __init__

The first is a constructor that can operate on the class, the second is, well, the _init_ializer that sets the instance.

One can debate about how to use each of them, but their defined role is not really questionable.

...or I really missed the sarcasm bit.

3

u/ThatOtherBatman 3d ago

Which gets even more nuanced when you ask the “class constructor” instead of “the constructor for the class”. Because I would argue that class constructor is __new__ in the metaclass.

-5

u/declspecl 3d ago

So you would say a constructor is the thing that instantiates an object, and not initializes? What would you say about constructors in C++ and Java for example? In both languages, the object is already instantiated by the time the `class Foo { Foo() { ... } }` Foo "constructor" is executed, which would indicate they they are initializers, not instantiators

3

u/aa-b 3d ago

I would say practical usage is the most important factor, instead of getting hung up on terminology. __new__ is really a metaprogramming thing, something you only rarely need for "normal" OOP. By comparison, __init__ is equivalent to a Java constructor, so you might as well just refer to it that way to keep things simple

1

u/ntropia64 3d ago

Due to Python nature, the difference between constructor and initializer is much fuzzier than than other languages, so in theory you could do everything that the __init__ does. I used it once to do precisely that and hijack the parameters passed to the init, which made me realize you can skip it altogether. In fact, that's what happens when creating singletons.

But basically if you follow the principle of least astonishment, new and init should have those well-defined roles so another programmer (like yourself from the future) doesn't have to make too much guessing to figure things out.

-5

u/declspecl 3d ago

Fully serious. The results are 50/50 so far, so it's definitely not as cut and dry as it may seem

2

u/yrubooingmeimryte 1d ago

Because python doesn’t use the concept of “constructor” in the way other languages do.