Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding __new__ and __init__ in Python [duplicate]

Tags:

python

Possible Duplicate:
Python's use of __new__ and __init__ ?

The way I understand it, __init__ is different from a constructor in Java, because __init__ only initializes an object that has already been constructed implicitly (because __init__ is called after __new__). However, everything that I have ever needed to define has used this latter property of a 'constructor' in Java. What would be a case in which a programmer would want to override __new__?

EDIT: For the record, I ask partly because I'm wondering what would be the advantage/disadvantage to overriding new vs. using a separate classmethod in the accepted answer to this question:

Moving Beyond Factories in Python

like image 621
chimeracoder Avatar asked Aug 27 '10 12:08

chimeracoder


2 Answers

__new__ actually happens before an object exists. It's a static method of the type. Uses of __new__ are when you want to control the creation of new objects, e.g. a singleton. If your __new__ always returns the same instance of an object, it's a singleton. You can't do that with __init__.

Generally, in "python as Guido intended it to be" you shouldn't use __new__ more than once a month :)

like image 125
abyx Avatar answered Nov 12 '22 08:11

abyx


__new__ is for creating new object instance, __init__ is for initializing it.

I think if you design an immutable type, you have to initialize it in __new__, see namedtuple for example (also Python's use of __new__ and __init__?).

like image 41
Constantin Avatar answered Nov 12 '22 08:11

Constantin