osdir.com


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

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


On Thursday, September 7, 2017 at 4:27:48 PM UTC+5:30, Andrej Viktorovich wrote:
> Hello
> 
> 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)

If you are not sure, forget about __new__
__init__ is the one you need mostly
[Ive never used new (in Python); C++ is a different case altogether]

See
https://mail.python.org/pipermail/tutor/2008-April/061424.html
and further thread