What is a Constructor in Python
Constructors are normally used for instantiating an object. The constructors are used to initialize(assign values) to the data members of the class when an object of class is created. In Python the __init__() method is called the constructor and is always called when an object is created.
Syntax of constructor declaration :
def __init__(self):
# body of the constructor
There are two types of constructors :
- Default constructor: The default constructor is a simple constructor that doesn’t accept any arguments. Its definition has only one argument which is a reference to the instance being constructed.
- Parameterized constructor: Constructor with parameters is known as parameterized constructor. The parameterized constructor takes its first argument as a reference to the instance being constructed known as self and the rest of the arguments are provided by the programmer.
Example of Default constructor:
# default constructor example class pet: def __init__(self): self.pet = "Pets" def display(self): print(self.pet) ob = pet() ob.display()
Output:
Pets
Example of parameterized constructor:
# parameterized constructor # example class pet: # parameterized constructor def __init__(self, name, color): self.name = name self.color = color def display(self): print("Name of pet: "+ str(self.name)) print("Color of pet: "+ str(self.color)) ob = pet('Jimmy', 'Black') ob.display()
Output:
Name of pet: Jimmy Color of pet: Black
Subscribe
Login
Please login to comment
0 Discussion