3 ms·
I am not a Python expert, but I think strictly speaking __init__ is the object instance initialiser. The "constructor" is the __new__ method (which is a static
by teh_klev 5y ago
I am not a Python expert, but I think strictly speaking __init__ is the object instance initialiser.
The "constructor" is the __new__ method (which is a static method) which will create an instance of the class. Afterwards a call is made to the __init__ method on the new instance, passing any parameters specified in the __new__ method and the newly created instance (as self).
As kissgyorgy rightly points out, it's the interpreter that performs these calls.
Python is a bit more revealing about how the sausages are made.
https://docs.python.org/3.10/reference/datamodel.html#object.__new__ https://docs.python.org/3.10/reference/datamodel.html#object...
https://docs.python.org/3.10/reference/datamodel.html#object.__init__ https://docs.python.org/3.10/reference/datamodel.html#object...
- ptx 5y agoHmm, perhaps there is no such thing as a constructor in Python then? As the documentation says, "__new__() and __init__() work together in constructing objects". In Java's constructors you already have access to the instance (and could leak it outside the object if you wanted to) whereas in __new__ you don't, so it doesn't seem like __new__ by itself could be called the constructor either.
- kissgyorgy 5y agoYes, because only at the end of __new__ AND __init__ would the object be complete.
- kissgyorgy 5y agoAgain, this is what I'm talking about. If you don't know the exact details, why do you want to teach how it works? Learn it first, try it, THEN teach about it. Silence or questions arebetter when you don't exactly know how things work. __new__ doesn't call __init__, the interpreter will call the __init__ when an instance is returned from __new__, otherwise it won't even be called.
- teh_klev 5y agoOk, mea culpa. However... In the __new__ method docs they mention an "object constructor expression" which I take to mean: person = Person("Bob", "Smith") And in the __init__ method docs there's mention of a "class constructor expression" which I also take to mean the same as above. Yet oddly we have no mention of constructors or constructor expressions in: https://docs.python.org/3/tutorial/classes.html https://docs.python.org/3/tutorial/classes.html And the act of instantiating a new instance of a class is referred to as "“calling” a class object)" https://docs.python.org/3/tutorial/classes.html#class-objects https://docs.python.org/3/tutorial/classes.html#class-object... Would you not agree that the docs could be a bit more consistent with regards to terminology?
- deleted 5y ago[deleted]