Google News
logo
Python Constructors
A constructor is a class function that begins with double underscore (_) or method (function) that is called when it instantiates an object using the definition found in your class. 
In Python, constructors are defined by one or both of __new__ and __init__ methods. A new instance is created by calling the class as if it were a function, which calls the __new__ and __init__ methods. If a constructor method is not defined in the class, the next one found in the class's Method Resolution Order will be called. In the typical case, only the __init__ method need be defined. (The most common exception is for immutable objects.)
>>> class My_Class(object):
	def __new__(cls, value):
		print("Creating new instance...")
		# Call the superclass constructor to create the instance.
		instance = super(My_Class, cls).__new__(cls)
		return instance
	def __init__(self, value):
		print("Initialising instance...")
		self.payload = value

		
>>> sampleInstance = My_Class(36)
Creating new instance...
Initialising instance...
>>> print(sampleInstance.payload)
36
>>> 

Python Destructors

The destructor is defined using __del__(self). In the example, the obj is created and manually deleted, therefore, both messages will be displayed. However, if you comment out the last line ‘del obj’, the destructor will not be called immediately. Instead, the Garbage Collector (GC) will take care of the deletion automatically, which you never know when for sure.

>>> class Test_1:
	def __init__(self):
		print ("constructor")
        
	def __del__(self):
		print ("destructor")

		
>>> print ("constructor")
constructor
>>> obj = Test_1()
constructor
>>> del obj
destructor
>>>