osdir.com


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

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


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)