ducin
ducin

Reputation: 26467

Real world example of overriding __new__ method in Python

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?

Upvotes: 3

Views: 555

Answers (1)

Mikhail Elizarev
Mikhail Elizarev

Reputation: 975

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.

Upvotes: 2

Related Questions