python 销毁函数_Python析构函数-销毁对象

python 销毁函数

Just like a constructor is used to create and initialize an object, a destructor is used to destroy the object and perform the final clean up.

就像使用构造函数创建和初始化对象一样,使用析构函数破坏对象并执行最终清理。

Although in python we do have garbage collector to clean up the memory, but its not just memory which has to be freed when an object is dereferenced or destroyed, it can be a lot of other resources as well, like closing open files, closing database connections, cleaning up the buffer or cache etc. Hence when we say the final clean up, it doesn't only mean cleaning up the memory resources.

尽管在python中我们确实有垃圾收集器来清理内存,但是它不仅是在取消引用或销毁对象时必须释放的内存,它还可能还有很多其他资源,例如关闭打开的文件,关闭数据库连接,清理缓冲区或缓存等。因此,当我们说最后清理时 ,这不仅意味着清理内存资源。

In our last tutorial we learned how object is created using __new__ method and initialised using the __init__ method. In this tutorial, we will learn how to destroy the object.

在上一教程中,我们学习了如何使用__new__方法创建对象以及如何使用__init__方法初始化对象。 在本教程中,我们将学习如何销毁对象。

As we specified clearly in the last tutorial, that __init__ method is not necessarily the constructor method as it is only repsonsible to initialise the object variables and not create the object, which is done by __new__ method.

正如我们在上一教程中明确指出的那样, __init__方法不一定是构造函数方法,因为它只负责初始化对象变量而不创建对象,这是由__new__方法完成的。

Similarly, the concept of destructors is also a little blur in python, although commonly __del__ method is considered as the destructor method, so lets see how we can use this method to destroy a class's object.

类似地,尽管通常将__del__方法视为析构函数方法,但在python中,析构函数的概念也有些模糊。因此,让我们看看如何使用此方法来破坏类的对象。

使用__del__方法 (Using the __del__ method)

Below we have a simple code for a class Example, where we have used the __init__ method to initialize our object, while we have defined the __del__ method to act as a destructor.

下面我们有一个用于Example类的简单代码,其中使用__init__方法初始化对象,同时定义__del__方法充当析构函数。

class Example:
	def __init__(self):
		print ("Object created");
	
	# destructor
	def __del__(self):
	    print ("Object destroyed");

# creating an object
myObj = Example();
# to delete the object explicitly
del myObj;

Object created Object destroyed

创建的对象销毁的对象

几点注意事项 (Few Points to Note)

  1. Like Destructor is counter-part of a Constructor, function __del__ is the counter-part of function __new__. Because __new__ is the function which creates the object.

    像析构函数是一个构造函数的反一部分,功能__del__是函数的反部分__new__ 。 因为__new__是创建对象的函数。

  2. __del__ method is called for any object when the reference count for that object becomes zero.

    当对象的引用计数变为零时,将为该对象调用__del__方法。

  3. As reference counting is performed, hence it is not necessary that for an object __del__ method will be called if it goes out of scope. The destructor method will only be called when the reference count becomes zero.

    由于执行了引用计数,因此,如果对象__del__方法超出范围,则不必调用该对象。 仅当引用计数为零时,才会调用析构函数方法。

极端案例:当析构函数表现不佳时 (Corner Cases: When Destructor doesn't behave well)

As we already mentioned in the start that using __del__ is not a full proof solution to perform the final clean up for an object which is no longer required.

正如我们在开始时已经提到的那样,使用__del__并不是对不再需要的对象执行最终清理的完整解决方案。

Here we have discussed two such situations where __del__ function behaves absurd.

在这里,我们讨论了__del__函数表现荒唐的两种情况。

1.循环引用 (1. Circular Referencing)

Circular referencing refers to a situation where two objects refers to each other. In such a case when both of these objects goes out of reference, python is confused to destroy which object first, and to avoid any error, it doesn't destroy any of them.

循环引用是指两个对象相互引用的情况。 在这两个对象都失去引用的情况下,python会迷惑首先破坏哪个对象,并且为了避免任何错误,它不会破坏它们中的任何一个。

Here is an example to demonstrate circular referencing,

这是演示循环引用的示例,

class Foo():
    def __init__(self, id, bar):
        self.id = id;
        # saving reference of Bar object
        self.friend = bar;
        print ('Foo', self.id, 'born');

    def __del__(self):
        (print 'Foo', self.id, 'died');


class Bar():
    def __init__(self, id):
        self.id = id;
        # saving Foo class object in variable
        # 'friend' of Bar class, and sending
        # reference of Bar object for Foo object
        # initialisation
        self.friend = Foo(id, self);
        print ('Bar', self.id, 'born')

    def __del__(self):
        print ('Bar', self.id, 'died')


b = Bar(12)

Foo 12 born Bar 12 born

Foo 12出生Bar 12出生

2. __init__方法中的异常 (2. Exception in __init__ method)

In object oriented progamming, destructor is only called in case an object is successfully created, because if the any exception occurs in the constructor then the constructor itself destroys the object.

在面向对象的编程中,仅在成功创建对象的情况下才调用析构函数,因为如果构造函数中发生任何异常,则构造函数本身会破坏该对象。

But in python, if any exception occurs in the __init__ method while initialising the object, in that case too, the method __del__ gets called.

但是在python中,如果初始化对象时__init__方法中发生任何异常,在这种情况下,也会调用__del__方法。

Hence, even though the object was never initialised correctly, the __del__ mehthod will try to empty all the resources and variables and in turn may lead to another exception.

因此,即使从未正确初始化该对象, __del__ del__方法也会尝试清空所有资源和变量,从而可能导致另一个异常。

class Example():
	def __init__(self, x):
	    # for x = 0, raise exception
		if x == 0:
			raise Exception();
		self.x = x;
		
	def __del__(self):
		print (self.x)

# creating an object
myObj = Example();
# to delete the object explicitly
del myObj

Exception exceptions.AttributeError: "'Example' object has no attribute 'x'" in > ignored

异常exception.AttributeError:在<__ main__的>处的Example对象

翻译自: https://www.studytonight.com/python/destructors-in-python

python 销毁函数

你可能感兴趣的:(数据库,python,编程语言,java,设计模式)