def __init__(self, [args ……..]): <statements>
Python Destructor is also a special method that gets executed automatically when an object exit from the scope. In Python, __del__( ) method is used as the destructor.
Examples of Constructor and destructor in Python
Simple example code:
Python constructor executed automatically when the object is created. This constructor function can have arguments.
class Sample: def __init__(self, num): print("Constructor of class Sample...") self.num = num print("The value is :", num) S = Sample(100)
Example program to illustrate the del( ) method
class Sample: num = 0 def __init__(self, var): Sample.num += 1 self.var = var print("Object value is = ", var) print("Variable value = ", Sample.num) def __del__(self): Sample.num -= 1 print("Object with value %d is exit from the scope" % self.var) S1 = Sample(10)
Object value is = 10
Variable value = 1
Object with value 10 is exit from the scope
When Constructor and destructor called in Python?
Answer: Constructor and destructor function automatically executed in Python. Constructor when an object of a class is created and Destructor when an object exit from the scope.
Do comment if you have any doubts and suggestions on this Python basic tutorial.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.