Search code examples
pythonnew-operatorinit

method is not getting called from within __new__


in the below code i attempt to understand init and new. The problem I am having is the method callBeforeInit() is never called.

Please let me know why it is not getting called and how to have it called.

code:

class varargs:

def __new__(cls):
    print("in object creation")
    callBeforeInit()
    return super(varargs, cls).__new__(cls)
    #return object.__new__(cls)

def __init__(self):
    print("in object indtansiation")

def callBeforeInit():
    print("called before init")

v = varargs()

error:

in object creation
Traceback (most recent call last):
File "d:\python workspace\Varargs.py", line 15, in <module>
v = varargs()
File "d:\python workspace\Varargs.py", line 5, in __new__
callBeforeInit()
NameError: name 'callBeforeInit' is not defined

Solution

  • new is called before creating an object, so there is no such method exist at this point.

    It should be

    class varargs:
    
        def __new__(cls):
            print("in object creation")
            cls.callBeforeInit()
            return super(varargs, cls).__new__(cls)
            #return object.__new__(cls)
    
        def __init__(self):
            print("in object indtansiation")
    
        @classmethod
        def callBeforeInit(cls):
            print("called before init")
    
    v = varargs()