Python __delete__() Magic Method

Python’s magic method __delete__() is called to delete an instance’s attribute. For example, the expression del my_obj.attr would result in attr.__delete__(my_obj), so you’d give the attribute itself the responsibility for its deletion on my_obj.

We call this a “Dunder Method” for Double Underscore Method” (also called “magic method”). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this blog.

Syntax and Example

object.__delete__(self, instance)

Let’s have a look at an example:

class My_Attribute:
    def __delete__(self, instance):
        print('hello world')
    
class MyClass:
    attr = My_Attribute()


my_obj = MyClass()
del my_obj.attr
# hello world

References:

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation. To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!