Destroy objects in python

Destructor in a Python class

Destructors are called when an object gets destroyed. It’s the polar opposite of the constructor, which gets called on creation.

These methods are only called on creation and destruction of the object. They are not called manually but completely automatic.

python destructor

A destructor can do the opposite of a constructor, but that isn’t necessarily true. It can do something different. A destructor is a function called when an object is deleted or destroyed.

An object is destroyed by calling:

Before the object is destroyed, you can do some final tasks. Imagine driving a Tesla and in the code the engine object gets destroyed. No, first you’d want to shutdown the engine, make sure the wheels are not spinning etc.

Take into mind that destroying an object with del is optional, you can create objects and never delete them. They are then only deleted when the program closes. However, this can eat up a lot of memory in large programs.

A destructor has this format:

It is always part of a class, even if not defined. (If not defined, Python assumes an empty destructor).

Example

The class below has a constructor (init) and destructor (del). We create an instance from the class and delete it right after.

An example of using destructor is shown in the code below:

class Vehicle:
def __init__(self):
print(‘Vehicle created.’)

def __del__(self):
print(‘Destructor called, vehicle deleted.’)

car = Vehicle() # this is where the object is created and the constructor is called
del car # this is where the destructor function gets called

If you run the above program, you can see this output in the terminal:

Vehicle created.
Destructor called, vehicle deleted.

The output is displayed, even though we didn’t call any methods. That’s because a constructor and destructor are called automatically.

Источник

How to destroy an object in Python?

When an object is deleted or destroyed, a destructor is invoked. Before terminating an object, cleanup tasks like closing database connections or filehandles are completed using the destructor.

The garbage collector in Python manages memory automatically. for instance, when an object is no longer relevant, it clears the memory.

In Python, the destructor is entirely automatic and never called manually. In the following two scenarios, the destructor is called −

  • When an object is no longer relevant or it goes out of scope
  • The object’s reference counter reaches zero.

Using the __del__() method

In Python, a destructor is defined using the specific function __del__(). For instance, when we run del object name, the object’s destructor is automatically called, and it then gets garbage collected.

Читайте также:  Java groupid and artifactid

Example 1

Following is an example of destructor using __del__() method −

# creating a class named destructor class destructor: # initializing the class def __init__(self): print ("Object gets created"); # calling the destructor def __del__(self): print ("Object gets destroyed"); # create an object Object = destructor(); # deleting the object del Object;

Output

Following is an output of the above code −

Object gets created Object gets destroyed

Note − The destructor in the code above is invoked either after the program has finished running or when references to the object are deleted. This indicates that the object’s reference count drops to zero now rather than when it leaves the scope.

Example 2

In the following example, we will use Python’s del keyword for destroying user-defined objects −

class destructor: Numbers = 10 def formatNumbers(self): return "@" + str(Numbers) del destructor print(destructor)

Output

Following is an output of the above code −

NameError: name 'destructor' is not defined

We get the above error as ‘destructor’ gets destroyed.

Example 3

In the following example, we will see −

class destructor: # using constructor def __init__(self, name): print('Inside the Constructor') self.name = name print('Object gets initialized') def show(self): print('The name is', self.name) # using destructor def __del__(self): print('Inside the destructor') print('Object gets destroyed') # creating an object d = destructor('Destroyed') d.show() # deleting the object del d

Output

We made an object using the code above. A reference variable called d is used to identify the newly generated object. When the reference to the object is destroyed or its reference count is 0, the destructor has been called.

Inside the Constructor Object gets initialized The name is Destroyed Inside the destructor Object gets destroyed

Things to Keep in Mind About Destructor

  • When an object’s reference count reaches 0, the __del__ method is invoked for that object.
  • When the application closes or we manually remove all references using the del keyword, the reference count for that object drops to zero.
  • When we delete an object reference, the destructor won’t be called. It won’t run until all references to the objects are removed.

Example

Let’s use the example to grasp the above mentioned principles −

  • Using d = destructor(«Destroyed»), first create an object for the student class.
  • Next, give object reference d to new object d1, using d1=d
  • Now, the same object is referenced by both d and d1 variables.
  • After that, we removed reference d.
  • In order to understand that destructors only functions when all references to the object are destroyed, we added a 10 second sleep period to the main thread.
import time class destructor: # using constructor def __init__(self, name): print('Inside the Constructor') self.name = name print('Object gets initialized') def show(self): print('The name is', self.name) # using destructor def __del__(self): print('Inside the destructor') print('Object gets destroyed') # creating an object d = destructor('Destroyed') # Creating a new reference where both the reference points to same object d1=d d.show() # deleting the object d del d # adding sleep and observing the output time.sleep(10) print('After sleeping for 10 seconds') d1.show()

Output

Destructors are only called, as you can see in the output, after all references to the objects are removed.

Читайте также:  Чат бот ватсап питон

Additionally, the destructor is called once the program has finished running and the object is ready for the garbage collector. (That is, we didn’t explicitly use del d1 to remove object reference d1).

Inside the Constructor Object gets initialized The name is Destroyed After sleeping for 10 seconds The name is Destroyed

Источник

Destructors in Python

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.

Python3

Employee 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.

Python3

Calling Create_obj() function. Making Object. Employee created function end. Program End. Destructor called

Example 3: Now, consider the following example :

Python3

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:

Читайте также:  Js получить значение css элемента

Python

('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.

Источник

Оцените статью