如果我有
class MyClass:
def __init__(self, object):
self.object = object
some_other_object = SomeOtherObject()
myclass = MyClass(some_other_object)
del myclass
some_other_object
发生了什么?它也被删除了吗?
如果整个程序中没有其他对some_other_object
的引用,那么是的,它也会被删除。
在您的案例中,有两个参考:1(some_other_object
和2(myclass.object
。
删除myclass
只会删除第二个引用。但第一个仍然存在。
Python使用一种称为"引用计数"的垃圾收集方法。简而言之,Python跟踪内存中每个对象的"引用"数量。如果运行del x
,则会将x
引用的对象的引用次数减少1(当然,名称x
不再引用该对象(。一旦对对象的引用数达到0,就可以对其进行垃圾回收(即可以释放其占用的内存(。
标题中有一个假设"如果删除一个包含另一个对象的对象,会发生什么">
实际上,使用del
并没有删除对象,而是删除了对对象的引用。当不再有对对象的引用时,它将被垃圾收集,然后它(以及其中的任何引用(才会被删除。
所以,在你的代码中:
class MyClass:
def __init__(self, object):
self.object = object
# A new object is created by SomeOtherClass() and assigned to some_other_object
some_other_object = SomeOtherClass()
# A new object is created by MyClass() and the my_object reference is created.
# Inside the new MyClass object my_object, a reference to some_other_object is saved.
my_object = MyClass(some_other_object)
# Here, the reference my_object is deleted, and thus the whole MyClass object is deleted.
# That includes the MyClass.object reference, but there's still the some_other_object reference.
del my_object
# Only now would that object be deleted, as the last reference is deleted.
del some_other_object
我已经重命名了您的一些变量和类,因为您正在混合它们——当然,类和对象之间有一个重要的区别,您应该相应地选择对象引用和类名(尽管通常会省略"对象"或"类"一词(。