ADVERTISEMENT
ADVERTISEMENT

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 »



ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.