Python-类析构函数__del__方法

时间:2020-02-23 14:42:30  来源:igfitidea点击:

在本教程中,我们将学习Python中的类__del__方法。

我们在Python-Classes and Objects教程中了解了类和对象。
随时检查一下。

__del__方法

__del__方法是类的一种特殊方法。

它也称为析构函数方法,并且在类的实例(对象)即将被销毁时被调用(调用)。

我们使用__del__方法来清理资源,例如关闭文件。

在下面的Python程序中,我们将在Awesome类中创建__del__方法。

# class
class Awesome:

    # some method
    def greetings(self):
        print("Hello World!")

    # the del method
    def __del__(self):
        print("Hello from the __del__ method.")

# object of the class
obj = Awesome()

# calling class method
obj.greetings()

上面的代码将打印以下输出。

Hello World!
Hello from the __del__ method.

注意点!

我们得到上面的输出,因为当代码即将结束时,不再需要类" Awesome",因此可以将其销毁。

在销毁类Awesome之前,会自动调用__del__方法。

垃圾收集

在Python中,任何不再使用的对象(例如内置类型或者类的实例)在不再使用时都会自动从内存中删除(删除)。

释放和回收未使用的内存空间的过程称为垃圾回收。

垃圾回收的概念在Java,C#,Python等语言中很常见。

在下面的Python程序中,我们将创建一个新文件并其中写入一些文本。
然后,我们使用__del__方法关闭文件。

在本教程中了解有关文件处理的更多信息。

# class
class Awesome:

    # the init method
    def __init__(self, filename):

        print("Inside the __init__ method.")

        # open file
        self.fobj = open(filename, "w")

    # method
    def writeContent(self, data):

        print("Inside the writeContent method.")

        # write the data
        self.fobj.write(data)

    # the del method
    def __del__(self):

        print("Inside the __del__ method.")

        # close file
        self.fobj.close()

# object
obj = Awesome("helloworld.txt")
obj.writeContent("Hello World")

运行上面的代码后,我们将获得以下输出。

Inside the __init__ method.
Inside the writeContent method.
Inside the __del__ method.