3

I'm familiar with the theory about __new__ vs __init__. The former one defines how an instance of a class is created (new object inside the memory), whereas the latter one initializes it (assigns initial state attributes - fields). There is a couple of articles in the web about this, such as this one:

Use __new__ when you need to control the creation of a new instance. Use __init__ when you need to control initialization of a new instance.

As I said, I do understand the difference, yet, I can't imagine a real world example of situation when I need to use __new__ instead of __init__. If I can customize something during object creation, I can move it to object initialization - as long as it's the same object. The mentioned link says:

In general, you shouldn't need to override __new__ unless you're subclassing an immutable type like str, int, unicode or tuple.

And here comes my question - can someone give an example of situation, when overriding __new__ is in fact the right solution that can't be done using __init__ and why is that?

tshepang
  • 12,111
  • 21
  • 91
  • 136
ducin
  • 25,621
  • 41
  • 157
  • 256
  • 1
    [Subclassing Python tuple with multiple \_\_init\_\_ arguments](http://stackoverflow.com/q/1565374) – Martijn Pieters Jun 09 '14 at 07:49
  • @MartijnPieters thank you for the link, but anyway, I'd appreciate a real world example. I guess that when you create an immutable tuple, you can do nothing with it inside __init__ since it's immutable by definition. – ducin Jun 09 '14 at 07:53
  • `__new__` is also useful when you have to do C level allocations. For example, you may have a pool of unused objects, expensive to initialize, so when you need a new one you just grab it from there instead of creating a full new one. – Davidmh Jun 09 '14 at 07:54
  • 1
    @tkoomzaaskz: "Real-world": https://docs.python.org/2/library/collections.html#collections.namedtuple Yes, you need `__new__` because by the time the instance is created it can no longer be changed. – Martijn Pieters Jun 09 '14 at 07:54
  • 1
    Another one: [Python and the Singleton Pattern](http://stackoverflow.com/q/42558) – Martijn Pieters Jun 09 '14 at 07:56

1 Answers1

2

Singletone pattern - the most obvious example. When you've created one more object - it is not the singletone, right? Thus, you have to handle this when you're creating your object. One variant of the solution - to use __new__() method.

Mikhail Elizarev
  • 965
  • 3
  • 10
  • 22