Constructor and Destructor in Python | INIT Method in python | Input and Output Method in Python Class
In Python constructors and destructor are special methods
used in class. They allow you to initialize and clean up objects respectively.
Here’s how you can define a constructor and destructor in python
Constructor
The constructor method is called when an object is created
from a class. It is used to initialize the attributes of the object. In Python
the constructor is defined using the __init__ Method
Example
def __init__(self):
print("init function")
Destructor
The destructor method is called when an object is about to
be destroyed or cleaned up. It is used to perform any necessary cleanup
operation the object is removed from memory. In python the destructor is
defined using the __del__ method
Example
def __del__(self):
print("destructor call")
Program Source Code:
import os
class student:
def __init__(self):
print("init function")
self.mark = 60
def show(self):
objshow = student()
print("marks :",self.mark)
os.system("pause")
objshow.display()
def display(self):
print("in display function")
def __del__(self):
print("destructor call")
obj1 = student()
os.system("pause")
obj1.show()
os.system("pause")
obj3 = student()
obj3.display()
Related Video
Input Method
To handle input, you can define a method in your class that
prompts the user for input or accepts input as parameters. This method can then
process the input and update the object’s attributes accordingly
Example
def inputMethod(self):
self.rollno = int(input("Enter Rollno :"))
self.name = input("Enter Name :")
self.grade = input("Enter Grade:")
Output Method
To handle output you can define a method in your class that formats
and displays the object’s data or returns it as a result
Example
def display(self):
print("rollno :",self.rollno)
print("Name :",self.name)
print("Grade :",self.grade)
Program Source Code
class student:
def inputMethod(self):
self.rollno = int(input("Enter Rollno :"))
self.name = input("Enter Name :")
self.grade = input("Enter Grade:")
def display(self):
print("rollno :",self.rollno)
print("Name :",self.name)
print("Grade :",self.grade)
ali = student()
print("--------Input Student Data--------------")
ali.inputMethod()
print("--------Output Student Data--------------")
ali.display()
Post a Comment