How to use "__new__"?

could ildg could.net at gmail.com
Tue Mar 29 20:27:17 EST 2005


Thank you.
I'm clear after I read the doc:
If __new__() returns an instance of cls, then the new instance's
__init__() method will be invoked like "__init__(self[, ...])", where
self is the new instance and the remaining arguments are the same as
were passed to __new__().

If __new__() does not return an instance of cls, then the new
instance's __init__() method will not be invoked.

__new__() is intended mainly to allow subclasses of immutable types
(like int, str, or tuple) to customize instance creation.


On Tue, 29 Mar 2005 18:12:41 -0700, Steven Bethard
<steven.bethard at gmail.com> wrote:
> could ildg wrote:
> > As there is already __init__, why need a __new__?
> > What can __new__ give us while __init__ can't?
> > In what situations we should use __new__?
> > And in what situations we must use __new__?
> > Can __new__ take the place of __init__?
> 
> I believe the current documentation will be updated when 2.4.1 is
> released, but documentation for __new__ is now available at:
> 
> http://www.python.org/dev/doc/devel/ref/customization.html
> 
> In short, you could use __new__ in place of __init__, but it's probably
> only useful to do so if you need to change an instance *before* it's
> created.  In general, if you aren't subclassing an immutable type, and
> you're not sure that you need __new__, you probably don't.
> 
> STeVe
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list