28
loading...
This website collects cookies to deliver better user experience
The task of constructors is to initialize(assign values) to the data members of the class when an object of class is created. A constructor can optionally accept arguments as well, just like a regular function.
__init__
keyword.class sample:
def __init__(self):
print("Class instantiated")
mysample=sample()
Class instantiated
self
keyword will geneate errorclass sample:
def __init__():
print("Class instantiated")
mysample=sample()
Traceback (most recent call last):
File "main.py", line 5, in <module>
mysample=sample()
TypeError: __init__() takes 0 positional arguments but 1 was given
__init__
method runs once class is instantiated. class sample:
def __init__(self):
print("Class instantiated")
mysample=sample()
mysample.__init__()
Class instantiated
Class instantiated
class sample:
def __init__(self):
print("Class instantiated")
def fun(self):
self.__init__()
print("inside a function")
mysample=sample()
mysample.fun()
Class instantiated
Class instantiated
inside a function
Remember this When you create a class without a constructor, Python automatically creates a default constructor for you that doesn't do anything. Every class must have a constructor, even if it simply relies on the default constructor.
The users call Destructor for destroying the object. In Python, developers might not need destructors as much it is needed in the C++ language. This is because Python has a garbage collector whose function is handling memory management automatically. The __del__()
function is used as the destructor function in Python. The user can call the __del__()
function when all the references of the object have been deleted, and it becomes garbage collected.
__init__
constructor.class sample:
rate=3
def __init__(self,amount):
self.amount=amount
def calculate_tax(self):
print(self.rate*self.amount*0.01)
mysample=sample(200)
mysample.calculate_tax()
6.0
Python does not support explicit multiple constructors, yet there are some ways using which the multiple constructors can be achieved. If multiple __init__
methods are written for the same class, then the latest one overwrites all the previous constructors
class sample:
rate=3
def __init__(self,amount):
self.amount=amount
def __init__(self,amount,rate):
self.amount=amount
self.rate=rate
def calculate_tax(self):
print(self.rate*self.amount*0.01)
mysample=sample(200)
mysample.calculate_tax()
Traceback (most recent call last):
File "main.py", line 13, in <module>
mysample=sample(200)
TypeError: __init__() missing 1 required positional argument: 'rate'
*args
But that's not for today....Python natively does not support function overloading - having multiple functions with the same name.