DEV Community

Discussion on: Python: __init__() is not the only constructor

Collapse
 
canizalesdiaz profile image
Jorge Cañizales Díaz • Edited

__new__ is what Objective-C and C++ would call an allocator: Its responsibility is to decide what "chunk of memory" to use for a new object.

Calling super().__new__ is the default behavior of allocating new memory in the heap and using that.

But for performance-critical code, you could implement a memory pool (or "arena") by selecting objects out of a contiguous array.

Or, if your class should have value semantics, you can cache new objects by value and have __new__ return already-existing objects. This technique is useful in other contexts too: Java does it automatically for small numerical objects and small strings (which are immutable, so caching them this way improves runtime and memory). Another context you might want to do it is for an object that represents a remote resource: Having only one local object per remote instance simplifies its code considerably when it comes to locking and caching remote state.

Should you call __new__ a constructor and say __init__ isn't a constructor? It doesn't matter. Although I think it's confusing for people familiar with other languages to say __init__ isn't the constructor, and kinda moot if one doesn't offer a better description for it.