How to create constructors in python

if init can’t be a constructor how we can create constructors in python like in other languages like c++, java

Hi @shankarmulakalapalli_a9515409b9f01ffd

  • __init__() is not a constructor. The self as the first parameter which is nothing but the object itself i.e object already exists.

  • __init__() is called immediately after the object is created and is used to initialize it.

The answer is __new__()

__new__(cls, *args, **kwargs) # signature

__new__() takes cls as the first parameter which represents the class that is needed to be instantiated, and the compiler automatically provides this parameter at the time of instantiation. args and **kwargs are arguments to be passed.

__new__ () is always called before __init__()

Example:

class Power:

def __new__(cls,*args):
    print("new method")
    print(cls)
    print(args)
    obj = super().__new__(cls)  #create our object and return it
    return obj

def __init__(self,n):         
    print("init method")
    self.n=n

def cal(self):
    return self.n**self.n

p=Power(5)
p.cal()

Output :

new method
<class ‘__main__.Power’>
(5,)
init method
3125

Hope this might helps :slight_smile:

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.