Python子对象删除顺序

时间:2018-09-10 01:50:12

标签: python del

我正在尝试了解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__()对象。有没有办法验证删除的顺序?

1 个答案:

答案 0 :(得分:0)

从输出中可以看到,Hello对象hello首先被删除,因为hello.obj仍然持有对SubObj对象的引用。删除hello后,将不再有对SubObj对象的引用,因此将其删除。

相关问题