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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class Person: # Constructor method def __init__(self, name, age): self.name = name # Initialize the name attribute self.age = age # Initialize the age attribute # Method to display person's details def display_info(self): print(f"Name: {self.name}, Age: {self.age}") # Creating objects of the Person class person1 = Person("Alice", 30) person2 = Person("Bob", 25) # Accessing and displaying attributes using the display_info method person1.display_info() # Output: Name: Alice, Age: 30 person2.display_info() # Output: Name: Bob, Age: 25 |
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