What are the options for using Python __new__?

I understand what it does __new__(and how it differs from __init__), so I'm not interested in definitions, I'm interested in when and how to use it __new__.

The documentation says:

In general, you do not need to redefine __new__, if you do not podklassifitsiruete immutable type type str, int, unicodeortuple

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 if necessary in this case).

So when, why, and how do you use it __new__?

I'm interested in use cases, not what he does (I know what he does).

+5
source share
2 answers

Answering a question, I used it to

  • create a singleton template (although there are ways to do this without using __new__)
  • dynamically extend classes from external modules without actually editing the source
  • set up classes in a metaclass (although __call__it can also be used, I think)
  • extend the class datetime.datetime(which is immutable) to return the current time if it was called without arguments, and the result of the call strptimein the argument if it was called with one string argument

__new__ , , , datetime, __new__ , , . , __init__, , - , __new__.

+10

factory, .

0

All Articles