【问题标题】:What happens if you delete an object that holds another object?如果删除包含另一个对象的对象会发生什么?
【发布时间】:2021-01-09 19:55:13
【问题描述】:

如果我有

class MyClass:
    def __init__(self, object):
        self.object = object
some_other_object = SomeOtherObject()
myclass = MyClass(some_other_object)
del myclass

some_other_object 会发生什么?它也被删除了吗?

【问题讨论】:

标签: python


【解决方案1】:

如果在整个程序中没有其他对some_other_object 的引用,那么是的,它也会被删除。

在您的情况下,有两个参考:1)some_other_object,和 2)myclass.object

删除myclass 只会删除第二个引用。但第一个仍然存在。

Python 使用一种称为“引用计数”的垃圾收集方法。简而言之,Python 会跟踪内存中每个对象的“引用”数量。如果您运行del x,您将减少对x 引用的对象的引用数量(当然,名称x 不再引用该对象)。一旦对象的引用数达到 0,就可以对它进行垃圾回收(即可以释放它占用的内存)。

【讨论】:

  • 太棒了!希望我对您有所帮助:)。
【解决方案2】:

标题中有一个假设“如果你删除一个持有另一个对象的对象会发生什么?”

您实际上并没有使用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 

我已经重命名了你的一些变量和类,因为你正在混合它们 - 当然,类和对象之间有一个重要的区别,你应该相应地选择你的对象引用和类名(尽管通常,单词 ' object' 或 'Class' 被省略)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-23
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    相关资源
    最近更新 更多