On Nov 19, 2019, at 14:30, Greg Ewing <greg.ew...@canterbury.ac.nz> wrote: > > On 20/11/19 6:51 am, Andrew Barnert via Python-ideas wrote: >> A class can bind attributes in __new__ and return a fully initialized >> object. If that’s perfectly ok, why doesn’t every class do everything >> in __new__, in which case there’s no reason for __init__ to exist at >> all? > > If Python had been designed with the ability to subclass built-in > immutable objects from the beginning, __init__ may well never have > existed.
I doubt it. For simple classes, __init__ is just easier to use. No need to write a magical pseudo-classmethod, to explicitly super, etc. When you don’t need the flexibility of being able to return an arbitrary instance (maybe even of a different type than was requested), or to override the MRO, or to set up immutable values or something else that’s impossible or at least conceptually wrong to do in __init__, you don’t want the extra complexity of __new__, and I don’t think Guido would have forced it on us. > I can't think of another language off the top of my head that splits > the functionality of object creation in quite this way. Off the top of my head, there’s Smalltalk, which I suspect is where Guido got the idea, and ObjC, which got it from Smalltalk, and Swift, which got it from ObjC, and Ruby, which got it from either Smalltalk or Python. And there are other languages outside the Smalltalk lineage that do two-phase construction. IIRC, Eiffel is sort of the reverse of Python, where the constructor implicitly calls new instead of vice versa, while Sather makes the constructor explicitly call new. C++ and its descendants don’t have two-phase initialization—but sometimes people hack it up manually; there’s a Design Pattern for it in Java. One use for it is needing to call virtual functions in the initializer (in C++11 and later, all of the cases where you actually couldn’t refactor your way out of that with no cost are solved, but it’s still sometimes convenient, or just familiar, to not do so). Sometimes it’s even about deferring exceptions, just like this discussion. _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/XEHMBHLLMXFM5TMMGHQNJUGN5LNYXEFD/ Code of Conduct: http://python.org/psf/codeofconduct/