8

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

Community
  • 1
  • 1
chimeracoder
  • 20,648
  • 21
  • 60
  • 60

2 Answers2

13

__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 :)

abyx
  • 69,862
  • 18
  • 95
  • 117
  • That makes sense. So is this (the accepted answer below) a case where overriding __new__ would also be appropriate? http://stackoverflow.com/questions/3571773/moving-beyond-factories-in-python – chimeracoder Aug 27 '10 at 12:28
3

__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__?).

Community
  • 1
  • 1
Constantin
  • 27,478
  • 10
  • 60
  • 79