DEV Community

Discussion on: Alternative Constructors in Python

thumbone profile image
Bernd Wechner

While I think it important indeed to understand the difference between __new__() and __init()__ I detect a degree of unnecessary hubris or smugness in any claim that one is the real constructor. They are simply differentiated by the fact that __new__ receives as its first argument the class object, and the __init__ receives as it's first argument the instantiated object. and that __new__ is tasked with returning an instance ... most other languages lack a clear analog because classes are not themselves objects as they are in Python (where basically everything is - an object that is). Nether is more real than the other.

It's true however that for the vast majority of use cases I have encountered, and by projection I suspect most people encounter, for constructors is do whatever is needed during instantiation of an object , without holding the undesired responsibility of actually creating and returning an instance). This is in fact, if we are to be pedantic,closer to what a C++ constructor is used for, than the responsibility __new__ carries with it, that is C++ constructors are also called with no instance creation responsibility, much rather in the context of an existing instance already (while it's not passed as an argument, it runs within in the scope of one).

All that said, your perfectly right, because Python does not support overloading of functions with different signatures, the traditional means of providing different construction paths is through differently named class methods that return an an instance (as __new__ is obliged to do).

p0intman profile image
P0intMaN Author

Great addition to the __init__() vs __new__() topic. My views were based on the practical understanding and I was being pretty restrictive when I said __new__() was the real constructor. I made this claim observing the fact that whenever you instantiate, in the backend, Python calls in __new__() first. Then, its the __new__() which "privately" calls __init__().

Yes, I strongly agree that both are called in while creating an object. The reason I was being defensive with __new__ is due to the strict definition of constructor I mentioned in the post and the fact that class makes an implicit call to __new__() while instantiating the object.

Again, this is purely debatable. It depends on the degree of freedom you add into the definition of constructor and purpose for which one had been using constructors for.