Q:

Constructor Initialization Example in Python

belongs to collection: Python class & object programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python class & object programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Parameterized Constructor and Destructor Example i... >>
<< Hierarchical Inheritance Example in Python...