Constructor and Destructor in Python Classes


In python, you can define classes using keyword class. The basic class skeleton that has a constructor and a destructor is given below.

#!/usr/bin/env python

class TestClass:
    
    def __init__(self):
        print ("constructor")

    def __del__(self):
        print ("destructor")

if __name__ == "__main__":
    obj = TestClass()
    del obj

The constructor is implemented using __init__(self) which you can define parameters that follows the self. The destructor is defined using __del__(self). In the example, the obj is created and manually deleted, therefore, both messages will be displayed. However, if you comment out the last line ‘del obj’, the destructor will not be called immediately. Instead, the Garbage Collector (GC) will take care of the deletion automatically, which you never know when for sure. For example, if you press F5 in the IDLE, only the first message will be displayed. However, if you run the program in the command line using python interpreter, both messages will be displayed no matter if you add ‘del obj’ or not.

If you raise an exception in the destructor, it will be ignored.

#!/usr/bin/env python

class TestClass:
    
    def __init__(self):
        print ("constructor")

    def __del__(self):
        print ("destructor")
        raise Exception("raise")

if __name__ == "__main__":
    obj = TestClass()
    del obj

It will display the following:

Exception Exception: Exception(‘raise’,) in <bound method TestClass.__del__ of <__main__.TestClass instance at 0x0000000002D67EC8>> ignored

The static methods can be defined using @staticmethod. You can use ‘Class.Method()’ or ‘Obj.Method()’ to invoke the method. For example,

#!/usr/bin/env python

class TestClass:

    @staticmethod
    def StaticMethod():
        print ("static")
    
    def __init__(self):
        print ("constructor")

    def __del__(self):
        print ("destructor")

if __name__ == "__main__":
    obj = TestClass()
    # the following both are ok.
    TestClass.StaticMethod() 
    obj.StaticMethod()
    del obj

It is noticed that here, given the above examples, all print are used as functions. This is to ensure the print is ok on both Python 2 and Python 3 i.e. Python 3 defines the print as a function, which you must use ‘(‘ and ‘)’ to include the parameters. However, in Python 2, you can use both.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
412 words
Last Post: Codeforces: B. Drinks
Next Post: Simple Multithreading in Python

The Permanent URL is: Constructor and Destructor in Python Classes

3 Comments

  1. sheela

Leave a Reply