Constructors in Python
Destructors are called when an object gets destroyed. In Python, destructors are not needed as much as in C++ because Python has a garbage collector that handles memory management automatically.
The __del__() method is a known as a destructor method in Python. It is called when all references to the object have been deleted i.e when an object is garbage collected.
Syntax of destructor declaration :
def __del__(self):
# body of destructor
Note : A reference to objects is also deleted when the object goes out of reference or when the program ends.
Example 1 : Here is the simple example of destructor. By using del keyword we deleted the all references of object ‘obj’, therefore destructor invoked automatically.
Python
# Python program to illustrate destructor
class Employee:
# Initializing
def __init__(self):
print('Employee created.')
# Deleting (Calling destructor)
def __del__(self):
print('Destructor called, Employee deleted.')
obj = Employee()
del obj
OutputEmployee created.
Destructor called, Employee deleted.
Note : The destructor was called after the program ended or when all the references to object are deleted i.e when the reference count becomes zero, not when object went out of scope.
Example 2: This example gives the explanation of above-mentioned note. Here, notice that the destructor is called after the ‘Program End…’ printed.
Python
# Python program to illustrate destructor
class Employee:
# Initializing
def __init__(self):
print('Employee created')
# Calling destructor
def __del__(self):
print("Destructor called")
def Create_obj():
print('Making Object...')
obj = Employee()
print('function end...')
return obj
print('Calling Create_obj() function...')
obj = Create_obj()
print('Program End...')
OutputCalling Create_obj() function...
Making Object...
Employee created
function end...
Program End...
Destructor called
Example 3: Now, consider the following example :
Python
# Python program to illustrate destructor
class A:
def __init__(self, bb):
self.b = bb
class B:
def __init__(self):
self.a = A(self)
def __del__(self):
print("die")
def fun():
b = B()
fun()
In this example when the function fun() is called, it creates an instance of class B which passes itself to class A, which then sets a reference to class B and resulting in a circular reference.
Generally, Python’s garbage collector which is used to detect these types of cyclic references would remove it but in this example the use of custom destructor marks this item as “uncollectable”.
Simply, it doesn’t know the order in which to destroy the objects, so it leaves them. Therefore, if your instances are involved in circular references they will live in memory for as long as the application run.
NOTE : The problem mentioned in example 3 is resolved in newer versions of python, but it still exists in version < 3.4 .
Example: Destruction in recursion
In Python, you can define a destructor for a class using the __del__() method. This method is called automatically when the object is about to be destroyed by the garbage collector. Here’s an example of how to use a destructor in a recursive function:
Python
class RecursiveFunction:
def __init__(self, n):
self.n = n
print("Recursive function initialized with n =", n)
def run(self, n=None):
if n is None:
n = self.n
if n <= 0:
return
print("Running recursive function with n =", n)
self.run(n-1)
def __del__(self):
print("Recursive function object destroyed")
# Create an object of the class
obj = RecursiveFunction(5)
# Call the recursive function
obj.run()
# Destroy the object
del obj
Output('Recursive function initialized with n =', 5)
('Running recursive function with n =', 5)
('Running recursive function with n =', 4)
('Running recursive function with n =', 3)
('Running recursive function with n =', 2)
('Running recursive function with n =', 1)
Recursive function object destroyed In this example, we define a class RecursiveFunction with an __init__() method that takes in a parameter n. This parameter is stored as an attribute of the object.
We also define a run() method that takes in an optional parameter n. If n is not provided, it defaults to the value of self.n. The run() method runs a recursive function that prints a message to the console and calls itself with n-1.
We define a destructor using the __del__() method, which simply prints a message to the console indicating that the object has been destroyed.
We create an object of the class RecursiveFunction with n set to 5, and call the run() method. This runs the recursive function, printing a message to the console for each call.
Finally, we destroy the object using the del statement. This triggers the destructor, which prints a message to the console indicating that the object has been destroyed.
Note that in this example, the recursive function will continue running until n reaches 0. When n is 0, the function will return and the object will be destroyed by the garbage collector. The destructor will then be called automatically.
Advantages of using destructors in Python:
- Automatic cleanup: Destructors provide automatic cleanup of resources used by an object when it is no longer needed. This can be especially useful in cases where resources are limited, or where failure to clean up can lead to memory leaks or other issues.
- Consistent behavior: Destructors ensure that an object is properly cleaned up, regardless of how it is used or when it is destroyed. This helps to ensure consistent behavior and can help to prevent bugs and other issues.
- Easy to use: Destructors are easy to implement in Python, and can be defined using the __del__() method.
- Supports object-oriented programming: Destructors are an important feature of object-oriented programming, and can be used to enforce encapsulation and other principles of object-oriented design.
- Helps with debugging: Destructors can be useful for debugging, as they can be used to trace the lifecycle of an object and determine when it is being destroyed.
Overall, destructors are an important feature of Python and can help to ensure that objects are properly cleaned up and resources are not wasted. They are easy to use and can be useful for enforcing encapsulation and other principles of object-oriented design.
Destructors in Python – FAQs
What are Destructors in Python?
In Python, destructors are methods that are called when an object is about to be destroyed. Unlike in languages such as C++ where destructors are very critical for the manual deallocation of resources, Python has a garbage collector that handles memory management automatically. However, destructors can still be useful for cleaning up non-memory resources, such as closing files or network connections.
What is the __del__ Function in Python?
The __del__ method in Python is a special method known as a destructor. It is called when an object is about to be destroyed, which can happen when its reference count reaches zero, or when the Python interpreter shuts down. This method is typically used to perform any necessary cleanup, resource release, or other “finalization” actions.
Example of __del__:
class Resource:
def __init__(self):
print("Resource allocated")
def __del__(self):
print("Resource deallocated")
res = Resource()
del res # Explicitly deleting the object
Is __del__ Always Called?
The __del__ method is not guaranteed to be called for every object that is created. If a program terminates abruptly without completing a normal shutdown process, or if there are circular references within the object’s graph, __del__ may not be called. Additionally, if an objectâs deletion is postponed (due to lingering references in other scopes), its __del__ method might be delayed. Thus, relying solely on __del__ for important cleanup tasks is generally discouraged.
What is __repr__ in Python?
The __repr__ method in Python is a special method used to obtain a string representation of an object that is as unambiguous as possible and can be used to recreate the object when fed to the eval() function. Itâs meant primarily for debugging and development. A good rule of thumb is to try to return a string that, when passed to eval(), would recreate the object with the same initial state.
Example of __repr__:
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f"Point({self.x}, {self.y})"
p = Point(1, 2)
print(repr(p)) # Output: Point(1, 2)
What is the Difference Between Constructor and Destructor in Python?
- Constructor: In Python, the constructor is the
__init__ method. It is automatically called when a new object of a class is created. It is used to initialize the attributes of the new object and can accept arguments to assign initial values to these attributes. - Destructor: The destructor method in Python is
__del__. It is called when an object is about to be destroyed, though its invocation is not guaranteed. While the constructor is for setting up things, the destructor is for cleanup activities.
Similar Reads
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Classes and Objects
A class in Python is a user-defined template for creating objects. It bundles data and functions together, making it easier to manage and use them. When we create a new class, we define a new type of object. We can then create multiple instances of this object type. Classes are created using class k
6 min read
Python objects
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to
2 min read
Class and Object
self in Python class
Self represents the instance of the class. By using the "self" we can access the attributes and methods of the class in Python. It binds the attributes with the given arguments. The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes. Python decid
6 min read
Class and Instance Attributes in Python
Class attributes: Class attributes belong to the class itself they will be shared by all the instances. Such attributes are defined in the class body parts usually at the top, for legibility. [GFGTABS] Python # Write Python code here class sampleclass: count = 0 # class attribute def increase(self):
2 min read
Create a Python Subclass
In Python, a subclass is a class that inherits attributes and methods from another class, known as the superclass or parent class. When you create a subclass, it can reuse and extend the functionality of the superclass. This allows you to create specialized versions of existing classes without havin
3 min read
Inner Class in Python
Python is an Object-Oriented Programming Language, everything in Python is related to objects, methods, and properties. A class is a user-defined blueprint or a prototype, which we can use to create the objects of a class. The class is defined by using the class keyword. Example of class [GFGTABS] P
5 min read
Python MetaClasses
The key concept of python is objects. Almost everything in python is an object, which includes functions and as well as classes. As a result, functions and classes can be passed as arguments, can exist as an instance, and so on. Above all, the concept of objects let the classes in generating other c
9 min read
Creating Instance Objects in Python
In Python, an instance object is an instantiation of a class, and it is a unique occurrence of that class. Creating instance objects is a fundamental concept in object-oriented programming (OOP) and allows developers to work with and manipulate specific instances of a class. This article will explor
3 min read
Dynamic Attributes in Python
Dynamic attributes in Python are terminologies for attributes that are defined at runtime, after creating the objects or instances. In Python we call all functions, methods also as an object. So you can define a dynamic instance attribute for nearly anything in Python. Consider the below example for
2 min read
Constructors in Python
In Python, a constructor is a special method that is called automatically when an object is created from a class. Its main role is to initialize the object by setting up its attributes or state. The method __new__ is the constructor that creates a new instance of the class while __init__ is the init
3 min read
Why Python Uses 'Self' as Default Argument
In Python, when defining methods within a class, the first parameter is always self. The parameter self is a convention not a keyword and it plays a key role in Pythonâs object-oriented structure. Example: [GFGTABS] Python class Car: def __init__(self, brand, model): self.brand = brand # Set instanc
3 min read
Encapsulation and Access Modifiers
Encapsulation in Python
In Python, encapsulation refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit, typically a class. It also restricts direct access to some components, which helps protect the integrity of the data and ensures proper usage. Table of Content En
6 min read
Access Modifiers in Python : Public, Private and Protected
Prerequisites: Underscore (_) in Python, Private Variables in Python Encapsulation is one of the four principles used in Object Oriented Paradigm. It is used to bind and hide data to the class. Data hiding is also referred as Scoping and the accessibility of a method or a field of a class can be cha
9 min read
Access Modifiers in Python : Public, Private and Protected
Prerequisites: Underscore (_) in Python, Private Variables in Python Encapsulation is one of the four principles used in Object Oriented Paradigm. It is used to bind and hide data to the class. Data hiding is also referred as Scoping and the accessibility of a method or a field of a class can be cha
9 min read
Private Variables in Python
Prerequisite: Underscore in PythonIn Python, there is no existence of âPrivateâ instance variables that cannot be accessed except inside an object. However, a convention is being followed by most Python code and coders i.e., a name prefixed with an underscore, For e.g. _geek should be treated as a n
3 min read
Private Methods in Python
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP) in Python. It describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of
6 min read
Protected variable in Python
Prerequisites: Underscore ( _ ) in Python A Variable is an identifier that we assign to a memory location which is used to hold values in a computer program. Variables are named locations of storage in the program. Based on access specification, variables can be public, protected and private in a cl
2 min read
Inheritance
Inheritance in Python
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called a child or derived class) to inherit attributes and methods from another class (called a parent or base class). This promotes code reuse, modularity, and a hierarchical class structure. In this arti
7 min read
Method Overriding in Python
Method overriding is an ability of any object-oriented programming language that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, the same parameter
7 min read
Operator Overloading in Python
Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because '+' operator is overloaded by int class and str class. You might have noticed t
9 min read
Python super()
In Python, the super() function is used to refer to the parent class or superclass. It allows you to call methods defined in the superclass from the subclass, enabling you to extend and customize the functionality inherited from the parent class. Syntax of super() in PythonSyntax: super() Return : R
8 min read
Multiple Inheritance in Python
Inheritance is the mechanism to achieve the re-usability of code as one class(child class) can derive the properties of another class(parent class). It also provides transitivity ie. if class C inherits from P then all the sub-classes of C would also inherit from P. Multiple Inheritance When a class
5 min read
What Is Hybrid Inheritance In Python?
Inheritance is a fundamental concept in object-oriented programming (OOP) where a class can inherit attributes and methods from another class. Hybrid inheritance is a combination of more than one type of inheritance. In this article, we will learn about hybrid inheritance in Python. Hybrid Inheritan
3 min read
Multilevel Inheritance in Python
Python is one of the most popular and widely used Programming Languages. Python is an Object Oriented Programming language which means it has features like Inheritance, Encapsulation, Polymorphism, and Abstraction. In this article, we are going to learn about Multilevel Inheritance in Python. Pre-Re
3 min read
Multilevel Inheritance in Python
Python is one of the most popular and widely used Programming Languages. Python is an Object Oriented Programming language which means it has features like Inheritance, Encapsulation, Polymorphism, and Abstraction. In this article, we are going to learn about Multilevel Inheritance in Python. Pre-Re
3 min read
Special Methods and Testing