Python del self statement

Python del self does almost nothing it only deletes the local variable that is named self. Calling __del__ manually also achieves nothing except for running that method; it doesn’t delete anything.

What does ‘del self.self ‘ in an __init__ function mean?

The del self.self simply removes the unwanted self attribute on the object named by the name self.

__del__ is a reserved function in Python that is called when the last reference to an object is being deleted or goes out of scope.

Example Deleted Object Manually

Manually deleting the object using the del keyword.

class Car:
    def __init__(self):
        print("New Car")
        self.name = "BMW X3"
        self.max_speed = "220 mph"

    def display(self):
        print(f"Name: {self.name}")
        print(f"Max Speed: {self.max_speed}")

    def __del__(self):
        print("Destroying the Car")


# creating object
myCar = Car()

# calling the display function
myCar.display()

# manually deleting the object using the del keyword
del myCar

Output:

Python del self statement

Do comment if you have any doubts and suggestions on this Python basic tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.