I understand what __new__
does (and how it's different from __init__
) so I'm not interested in definitions, I'm interested in when and how to use __new__
.
The documentation says:
In general, you shouldn't need to override
__new__
unless you're subclassing an immutable type likestr
,int
,unicode
ortuple
But I can't think of other cases to use __new__
or how to use it correctly (for example when subclassing an immutable type or why it's needed in this case).
So, when, why and how do you need to use __new__
?
I'm interested in the use cases, not what it does (I know what it does).
Answering for myself, I've used it to
__new__
)__call__
may also be used I think)datetime.datetime
class (which is immutable) to return the current time if instanciated without arguments and the result of calling strptime
on the argument if called with a single string argumentYou need __new__
when subclassing an immutable type if you want to alter the arguments used to construct the immutable, as I wanted in the datetime
example, or if you don't want to call the parent __new__
at all but return an instance created another way or even of an entirely different type. By the time you're in __init__
it's too late to alter the object in any way, so you need to do it in __new__
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With