del to delete objects in Python

We can delete objects or variables in Python by using del keyword.

Deleting an object

Here is a class declaration with one method to display welcome message. Outside the class we are declaring object and displaying the message by using the register method. Once the object is deleted by del then same method will generate NameError as the object is no longer available.
class student_kit():
  
  def register(self,name):# method declaration 
    self.name=name        
    print("Welcome:",self.name)

s1=student_kit() # object declaration
s1.register('Alex')
del s1
s1.register('Ron') # NameError
The last line in above code will generate error. We can use try except error handling to manage the error.
class student_kit():
  def register(self,name):# method declaration 
    self.name=name        
    print("Welcome:",self.name)

try:
  s1=student_kit() # object declaration
  s1.register('Alex')
  del s1
  s1.register('Ron') # NameError
except NameError as my_msg:
    print ("This is a NameError")
    print(my_msg)
except:
    print ("Some other error has occurred")
Output
Welcome: Alex
This is a NameError
name 's1' is not defined
Her we have deleted the object of a user defined class. In python everything is an object so del can delete list, dictionary, variable etc.

del with list

We can delete any element of the list
my_list=['a','b','c','d']
del my_list[1]
print(my_list)
Output
['a', 'c', 'd']
Deleting the list.
my_list=['a','b','c','d']
del my_list
print(my_list) # NameError
The last line will generate NameError.

del with dictionary

We will delete one element of a dictionary
my_dict={1:'Alex',2:'Ronald'}
print(my_dict)
del my_dict[2]
print(my_dict)
Output is here
{1: 'Alex', 2: 'Ronald'}
{1: 'Alex'}
We can delete the dictionary, here the change in line 3 is only displayed. This will generate error.
del my_dict

del with variable

In python all are objects only. Here is one integer object a ( variable ) . We will delete the object and again try to print the value.
a=6
print(a) # 6
del a
print(a) # error
The last line will generate error. We can use try except error handling to manage the error.
a=6
try:
  print(a) # 6
  del a
  print(a) # error 
except NameError as my_msg:
    print ("This is a NameError")
    print(my_msg)
except:
    print ("Some other error has occured")
Output
6
This is a NameError
name 'a' is not defined
Reserved Keywords in Python variables in Python


Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer