删除对象时出现意外输出

Unexpected output when deleting object

当我尝试删除 class 的一个实例时,它导致另一个实例的 __del__ 方法出现意外输出:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print('{0} has been born!'.format(self.name))

    def __str__(self):
        return '{0} is {1} years old'.format(self.name, self.age)

    def __del__(self):
        print('{0} is deleted!'.format(self.name))

p1 = Person("John", 20)
p2 = Person("Mary", 27)

print(p1)
print(p2)

del(p2)

输出为:

John has been born!
Mary has been born!
John is 20 years old
Mary is 27 years old
Mary is deleted!
John is deleted!

为什么"John is deleted!"

John 已被删除,因为您的脚本结束了。那时所有模块全局变量都被清除。

需要说明的是,这里并不是 del 调用清除了 Marydel 只是从全局命名空间中清除变量,这又会减少对该对象的引用计数。一旦引用计数达到 0,就会调用 __del__ 方法并将对象从内存中清除。

但是你的脚本命名空间也是一个对象;它存储在 __main__ 键下的 sys.modules 中,一旦完成 运行,Python 解释器退出并清除 sys.modules 中的所有模块。这会导致引用计数下降,对于 John 这意味着它也会被清除。

您可以在 del(p2) 之后添加 print 语句:

print('Script complete')

你会看到在 is deleted! 输出之间插入:

Mary is deleted!
Script complete
John is deleted!