And*_*nak 7 python destructor python-3.x
As far as I understand Python destructors should be called when the reference count of an object reaches 0. But this assumption seems not to be correct. Look at the following code:
class A:
def __init__(self, b):
self.__b = b
print("Construct A")
def __del__(self):
# It seems that the destructor of B is called here.
print("Delete A")
# But it should be called here
class B:
def __init__(self):
print("Construct B")
def __del__(self):
print("Delete B")
b = B()
a = A(b)
Run Code Online (Sandbox Code Playgroud)
Outputs
Construct B
Construct A
Delete B
Delete A
Run Code Online (Sandbox Code Playgroud)
But A has a reference to B, so I would expect the following output:
Construct B
Construct A
Delete A
Delete B
Run Code Online (Sandbox Code Playgroud)
What am I not getting?
因此,由于对象在解释器关闭时仍然存在,因此您实际上甚至不能保证__del__会被调用。在这一点上,语言不保证终结器何时被调用。
不能保证
__del__()在解释器退出时仍然存在的对象调用方法。
请注意,如果您将脚本更改为:
(py38) 173-11-109-137-SFBA:~ juan$ cat test.py
class A:
def __init__(self, b):
self.__b = b
print("Construct A")
def __del__(self):
# It seems that the destructor of B is called here.
print("Delete A")
# But it should be called here
class B:
def __init__(self):
print("Construct B")
def __del__(self):
print("Delete B")
b = B()
a = A(b)
del a
del b
Run Code Online (Sandbox Code Playgroud)
然后,执行:
(py38) 173-11-109-137-SFBA:~ juan$ python test.py
Construct B
Construct A
Delete A
Delete B
Run Code Online (Sandbox Code Playgroud)
虽然del确实不删除对象,它删除引用,所以它迫使引用计数到达0时解释仍在运行,所以顺序是你所期望的。
有时,__del__根本不会被调用。一个常见的情况是创建的文件对象
f = open('test.txt')
Run Code Online (Sandbox Code Playgroud)
在全局范围内具有实时引用。如果没有明确关闭,它可能不会调用__del__并且文件不会刷新并且您不会得到任何写入。这是使用文件对象作为上下文管理器的一个重要原因......
| 归档时间: |
|
| 查看次数: |
446 次 |
| 最近记录: |