[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Why do we nned both - __init__() and __new__()

Andrej Viktorovich <viktorovichandrej at gmail.com> writes:

> For my understanding both - __init__() and __new__() works like constructors. And __new__() looks is closer to constructor. __init__() is more for variable initialization. Why I can't just initialize in __init__() ?
> class ExampleClass(object):
>     def __new__(cls,value):
>         print("creating new instance with val %s" % (value,) )
>         instance = super(ExampleClass,cls).__new__(cls)
>         return instance
>     def __init__(self, value):
>         print("Initialising instance... with val %s" % (value,))
>         self.payload = value
> exampleInstance = ExampleClass(42)
> print(exampleInstance.payload)

In this special case (as others already explained, it is quite common),
you do not need "__new__".

In the general case, constructing an object can be split into two
subtasks: obtain a raw piece of storage able to manage the object's state;
initialize the object's state. The first subtask is handled by "__new__",
the second by "__init__".

Python has defaults for both subtasks -- and as others already pointed
out, the default "__new__" is almost always sufficient.