如何在 Python 中销毁对象?

programmingpythonserver side programming

当对象被删除或销毁时,将调用析构函数。在终止对象之前,使用析构函数完成清理任务,例如关闭数据库连接或文件句柄。

Python 中的垃圾收集器会自动管理内存。例如,当对象不再相关时,它会清除内存。

在 Python 中,析构函数是完全自动的,从不手动调用。在以下两种情况下,将调用析构函数 -

  • 当对象不再相关或超出范围时
  • 对象的引用计数器达到零。

使用 __del__() 方法

在 Python 中,使用特定函数 __del__() 定义析构函数。例如,当我们运行 del 对象名时,会自动调用该对象的析构函数,然后将其作为垃圾回收。

示例 1

以下是使用 __del__() 方法的析构函数示例 −

# creating a class named destructor class destructor: # initializing the class def __init__(self): print ("Object gets created"); # calling the destructor def __del__(self): print ("Object gets destroyed"); # create an object Object = destructor(); # deleting the object del Object;

输出

以下是上述代码的输出 

Object gets created
Object gets destroyed

注意 − 上述代码中的析构函数在程序运行完毕后或对象引用被删除时调用。这表示对象的引用计数现在降至零,而不是在离开范围时。

示例 2

在下面的示例中,我们将使用 Python 的 del 关键字来销毁用户定义的对象 −

class destructor: Numbers = 10 def formatNumbers(self): return "@" + str(Numbers) del destructor print(destructor)

输出

以下是上述代码的输出 

NameError: name 'destructor' is not defined

我们得到上述错误,因为"destructor"被销毁了。

示例 3

在下面的例子中,我们将看到−

  • 如何使用析构函数
  • 当我们删除对象时,如何调用析构函数?
class destructor: # using constructor def __init__(self, name): print('Inside the Constructor') self.name = name print('Object gets initialized') def show(self): print('The name is', self.name) # using destructor def __del__(self): print('Inside the destructor') print('Object gets destroyed') # creating an object d = destructor('Destroyed') d.show() # deleting the object del d

输出

我们使用上面的代码创建了一个对象。名为 d 的引用变量用于标识新生成的对象。当对该对象的引用被销毁或其引用计数为 0 时,将调用析构函数。

Inside the Constructor
Object gets initialized
The name is Destroyed
Inside the destructor
Object gets destroyed

关于析构函数需要注意的事项

  • 当对象的引用计数达到 0 时,将为该对象调用 __del__ 方法。
  • 当应用程序关闭或我们使用 del 关键字手动删除所有引用时,该对象的引用计数将降至零。
  • 当我们删除对象引用时,不会调用析构函数。直到删除对对象的所有引用后,它才会运行。

示例

让我们通过示例来掌握上述原则 -

  • 使用 d = destructor("Destroyed"),首先为学生类创建一个对象。
  • 接下来,使用 d1=d 将对象引用 d 赋予新对象 d1
  • 现在,d 和 d1 变量都引用了同一个对象。
  • 之后,我们删除了引用 d。
  • 为了理解析构函数仅在销毁对对象的所有引用时才起作用,我们在主线程中添加了 10 秒的休眠期。
import time class destructor: # using constructor def __init__(self, name): print('Inside the Constructor') self.name = name print('Object gets initialized') def show(self): print('The name is', self.name) # using destructor def __del__(self): print('Inside the destructor') print('Object gets destroyed') # creating an object d = destructor('Destroyed') # Creating a new reference where both the reference points to same object d1=d d.show() # deleting the object d del d # adding sleep and observing the output time.sleep(10) print('After sleeping for 10 seconds') d1.show()

输出

正如您在输出中看到的那样,只有在删除对对象的所有引用后,才会调用析构函数。

此外,一旦程序运行完毕并且对象已准备好进入垃圾收集器,就会调用析构函数。(也就是说,我们没有明确使用 del d1 来删除对象引用 d1)。

Inside the Constructor
Object gets initialized
The name is Destroyed
After sleeping for 10 seconds
The name is Destroyed

相关文章