__delete__ vs __del__ in Python

__delete__ vs __del__ in Python

Both __delete__ and __del__ are dunder or magic methods in Python. Dunder or magic methods in Python are the methods having two prefix and suffix underscores in the method name. Dunder here means “Double Under (Underscores)”. These are commonly used for operator overloading.

__delete__vs__del__ in Python

__del__

  • The __del__ method is similar to destructor in c++ and Java.
  • Destructors are used to destroying the object’s state. 

Syntax:

class ClassName:
def __del__( self ,):
##body

Code #1:

 
#python Program
#Rishikesh 
#destructor 
#__del__
 
class A(object): 
    def __init__(self): 
        self.str1 = “PrepInsta”
        print(“Object Created” , self.str1) 
    def __del__(self):
        print(‘Del is called’)
        
 

 

ob = A() 

Output: 

Object Created PrepInsta
Del is called

Note: The destructor was called after the program ended or when all the references to the object are deleted

__delete__

  • __delete__ is used to delete the attribute of an instance i.e Called to delete the attribute on an instance of the owner class.

Note: This method only deletes the attribute which is a descriptor.

Syntax

def __delete__(self, instance):
    body of delete
object__delete__(self, instance)
self
Required. An instance of the class, passed automatically on call.
delete vs del in python

Code #2


#python Program
#Rishikesh 
#__delete__
# this is our descriptor object
class Bar(object):
    def __init__(self):
        self.value = 
    def __get__(selfinstanceowner):
        print (“returned from descriptor object”)
        return self.value
    def __set__(selfinstancevalue):
        print (“set in descriptor object”)
        self.value = value
    def __delete__(selfinstance):
        print (“deleted in descriptor object”)
        del self.value

class Foo(object):
    bar = Bar()

f = Foo()
f.bar = 10
print (f.bar)
del f.bar

Output:

set in descriptor object
returned from descriptor object
10
deleted in descriptor object