Advertisements
Advertisements
प्रश्न
How to define constructor and destructor in Python?
संक्षेप में उत्तर
उत्तर
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
क्या इस प्रश्न या उत्तर में कोई त्रुटि है?