Python子对象删除顺序

问题描述 投票:0回答:1

我正在尝试了解python对象__del__()方法的工作原理。这是我正在尝试测试的一个例子:

class Hello(object):

    def __init__(self, arg1="hi"):
        print("in Hello __init__()")
        self.obj = SubObj()

    def __del__(self):
        print("in Hello __del__()")

    def test(self):
        print('in Hello obj.test().')


class SubObj(object):
    def __init__(self, arg1="hi"):
        print("in SubObj __init__()")

    def __del__(self):
        print("in SubObj __del__()")

    def test(self):
        print('in SubObj obj.test().')


if __name__ == '__main__':
    hello = Hello()
    from time import sleep

    hello.test()

    sleep(4)

所以该程序的输出如下:

$ python test_order.py 
in Hello __init__()
in SubObj __init__()
in Hello obj.test().
in Hello __del__()
in SubObj __del__()

SubObj总是先被删除吗?假设在Hello之后in SubObj __del__()对象被删除是否安全。有没有办法验证删除的顺序?

python del
1个回答
0
投票

正如您从输出中看到的那样,Hello对象hello首先被删除,因为hello.obj仍然拥有对SubObj对象的引用。删除hello后,不再有任何对SubObj对象的引用,因此将其删除。

© www.soinside.com 2019 - 2024. All rights reserved.