Constructor Initialization Example in Python

Here, we are going to learn about the Constructor Initialization in Python and going to demonstrate the example of Constructor Initialization in Python.
Submitted by Shivang Yadav, on February 15, 2021

Problem Statement: We need to create instances of an object using a constructor.

Problem Description: We will use Person class and create the instance of it using a constructor. Then accept the person’s information and print their details.

Algorithm:

  • Step 1: Create a class named Person to store information of person (name and age).
  • Step 2: Create the object of class and then input the information using getPersonDetails() method.
  • Step 3: Then we will print the information using printDetails() method.

Program to illustrate the constructor initialization

class Person:
    def __init__(self):
        print("Person Created[instantiate]")
    def getPersonDetails(self):
        self.name = input("Enter Name : ")
        self.age = int(input("Enter Age : "))
    def printDetails(self):
        print(self.name,self.age)

P1=Person()
P2=Person()
P1.getPersonDetails()
P2.getPersonDetails()
print("Printing details of the person...")
P1.printDetails()
P2.printDetails()

Output:

Person Created[instantiate]
Person Created[instantiate]
Enter Name : John
Enter Age : 34
Enter Name : Jane 
Enter Age : 32
Printing details of the person...
John 34
Jane  32

Python class & object programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.