English
Tamil Nadu Board of Secondary EducationHSC Science Class 12

How to define constructor and destructor in Python?

Advertisements
Advertisements

Question

How to define constructor and destructor in Python?

Answer in Brief
Advertisements

Solution

Constructor:

  • The constructor is the special function that is automatically executed when an object of a class is created.
  • In Python, there is a special function called “init” which acts as a Constructor.
  • It must begin and end with a double underscore.
  • This function will act as an ordinary function; but the only difference is, it is executed automatically when the object is created.
  • This constructor function can be defined with or without arguments. This method is used to initialize the class variables.

Syntax:
_init_ method (Constructor function)
def _init_(self, [args …. ]):
< statements >

Example:

class Sample:
def _init_(self, num):
print(” Constructor of class Sample…”)
self.num=num
print(“The value is :”, num)
S=Sample(10)

Destructor:

  • Destructor is also a special method that gets executed automatically when an object exit
  • from the scope.
  • It is just opposite to the constructor.
  • In Python, the _del_ () method is used as the destructor.

Example:

class Example:
def _init_ (self):
print “Object created”
# destructor
def _del_ (self):
print “Object destroyed”
# creating an object
myObj = Example ()

Output:
Object created
Object destroyed

shaalaa.com
Constructor and Destructor in Python
  Is there an error in this question or solution?
Chapter 10: Python Classes and objects - Evaluation [Page 188]

APPEARS IN

Samacheer Kalvi Computer Science [English] Class 12 TN Board
Chapter 10 Python Classes and objects
Evaluation | Q 5. | Page 188
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×