write a python program to demonstrate constructors

Python program to demonstrate constructors

Here you will learn to write a python program to demonstrate constructors.

Constructor is a special method that is automatically called when a new object of a class is created. Constructors are defined using the ‘__init__’ method within the class definition. The purpose of a constructor is to initialize the object’s attributes or perform any necessary setup actions when the object is created.

 

Example of python program to demonstrate constructors

Explanation:

Class Definition:

>> The ‘Person’ class is defined with an __init__ method, that is constructor.
>> The constructor takes ‘name’ and ‘age’ as parameters and initializes the object’s attributes(self.name and self.age).

 

Creating Objects:

>> ‘person1’ and ‘person2’ are objects of the ‘Person’ class.
>> When each object is created, the ‘__init__’ method is called with the provided ‘name’ and ‘age’ values.

 

Display Information:

>> The ‘display_info’ method print the ‘name’ and ‘age’ attributes of the objects.
>> This method is called for each object to display its details.

 

 

Check out our other Python programming examples

 

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top