many constructors in a class?

Roy Smith roy at panix.com
Thu Aug 15 09:00:27 EDT 2013


In article <520c81f6$0$29885$c3e8da3$5496439d at news.astraweb.com>,
 Steven D'Aprano <steve at pearwood.info> wrote:

> [1] The constructor is __new__, not __init__. __init__ is called to 
> initialise the instance after __new__ constructs it.

True, but be warned that writing your own __new__() is quite rare and 
probably falls into the realm of dark magic.  If you're just starting 
out, learn about __init__(), and don't worry about __new__() at all.

For those of you coming from a C++ background, Python's __init__() is 
like C++'s constructor, and __new__() is more like operator new.  That's 
not a perfect analogy from a functional standpoint, but it's a good 
guide for how often you'll want to write each one.

And then, of course, there's __enter__() and __exit__(), which are like 
C++'s constructor and destructor, but that's another story :-)



More information about the Python-list mailing list