Write a python program to Create Student Class with Constructor and Destructor
This Python code defines a Student class with a constructor, destructor, and methods for setting and displaying student data. Here's an explanation of the code:
- class Student:: This line defines a class named Student, which serves as a blueprint for creating student objects.
- def __init__(self):: This is the constructor method of the Student class. The constructor is automatically called when an instance of the class is created. Inside the constructor:
- Default values are assigned to instance variables (attributes) such as id, name, gender, total, and per.
- These attributes represent the student's ID, name, gender, total marks, and percentage.
- def __del__(self):: This is the destructor method of the Student class. The destructor is called when an object is about to be destroyed. In this case, it simply prints "Object Destroyed" when the object is destroyed.
- def setData(self):: This method allows you to set the data for a student instance. It prompts the user for input and sets the values of the student's attributes based on the user's input.
- def showData(self):: This method displays the data of the student. It prints the values of the student's attributes to the console.
- s = Student(): This line creates an instance of the Student class and assigns it to the variable s. This instance represents a specific student.
- s.setData(): The setData method is called on the s instance to set the data for this student. The user is prompted to enter the student's ID, name, gender, total marks, and percentage.
- s.showData(): The showData method is called on the s instance to display the student's data. It prints the values of the attributes set in the setData method.
When you run this program, it will create a Student object, set its attributes based on user input, and then display the student's information.
Source Code
class Student:
def __init__(self): #Constructor
self.id = 0
self.name = ""
self.gender = ""
self.total = ""
self.per = 0
def __del__(self): #Destructor
print("Object Destroyed")
def setData(self):
self.id = int(input("Enter a ID :"))
self.name = input("Enter a Name :")
self.gender = input("Enter a Gender :")
self.total = int(input("Enter a Total :"))
self.per = float(input("Enter a Percentage :"))
def showData(self):
print("Id :",self.id)
print("Name :", self.name)
print("Gender :", self.gender)
print("City :", self.total)
print("Salary :", self.per)
s = Student()# Create an instance of the Student class
s.setData()# Set data for the instance
s.showData()# Display data for the instance
Output
Enter a ID :10123
Enter a Name :Tiya
Enter a Gender :Female
Enter a Total :422
Enter a Percentage :84.4
Id : 10123
Name : Tiya
Gender : Female
City : 422
Salary : 84.4
Object Destroyed