__new__needed in Python development and when to use it?
There is a good comment in 2 words on what the magic method is
__new__: static method, called when the class is instantiated . In general, first he, then
__init__, I think I understood correctly.
I am ashamed to admit, but I have never seen in practice the application of this magical method, even on a simple toy example it looks superfluous.
class Foo(object): def __new__(cls, *args, **kwargs): print "Creating Instance" instance = super(Foo, cls).__new__(cls, *args, **kwargs) return instance def __init__(self, a, b): self.a = a self.b = b def bar(self): pass
Can someone give a simple example where there is a reasonable use of
__new__and explain why it is needed and when it should be used?
Answer 1, authority 100%
From official documentation :
is intended mainly to allow subclasses of immutable types (like int,
str, or tuple) to customize instance creation. It is also commonly
overridden in custom metaclasses in order to customize class creation.
class Singleton(object): _instance = None # Keep instance reference def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = object.__new__(cls, *args, **kwargs) return cls._instance
In : s1 = Singleton() In : s2 = Singleton() In : s1 is s2 Out: True
An example of use in the module pathlib ( from the standard library in Python 3.x):
class PurePath(object): ... def __new__(cls, *args): """Construct a PurePath from one or several strings and or existing PurePath objects. The strings and path objects are combined so as to yield a canonicalized path, which is incorporated into the new PurePath object. """ if cls is PurePath: cls = PureWindowsPath if os.name == 'nt' else PurePosixPath return cls._from_parts(args)
NOTE: if you are interested in examples of real and correct use of methods / functions in Python, then it is better to spy on how the authors of the Python standard library use them:
go to the
<Python_installation>/Libdirectory and look in which files the method you are interested in is present:
C:\Users\Max\Anaconda3\Lib>grep -l "def __new__(" *.py _py_abc.py _pydecimal.py _pyio.py _threading_local.py abc.py codecs.py datetime.py enum.py fractions.py functools.py pathlib.py pstats.py sre_constants.py ssl.py turtle.py typing.py weakref.py
open the files you find in the editor, find the lines you are interested in, and study the use cases from the creators of Python …