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

Andrej Viktorovich viktorovichandrej at gmail.com
Thu Sep 7 06:57:20 EDT 2017


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)



More information about the Python-list mailing list