[英]Destructor being called multiple times
我正在尝试检查new 、 init和del的工作方式以及在下面提到的代码下运行,引起我注意的是析构函数被调用了两次,我不知道它的确切原因,有人可以帮忙吗?
class Example:
# creation of new instance
def __new__(cls):
print("example created", object.__new__(cls))
return object.__new__(cls)
# Initializing
def __init__(self):
print("Example Instance.")
# Calling destructor
def __del__(self):
print("Destructor called, Example deleted.")
obj = Example()
del obj
来自 geeksforgeeks:
__del__() 方法在 Python 中被称为析构函数。 当对对象的所有引用都被删除时调用它,即当对象被垃圾回收时。 注意:当对象失去引用或程序结束时,对对象的引用也会被删除。
Python 使用引用计数和垃圾收集器自动为您管理内存。 也就是说,不需要的引用会被自动删除。
因此,您需要显式创建它以避免这种行为。
class Example:
instance = ""
# creation of new instance
def __new__(cls):
instance = object.__new__(cls)
print("example created", instance)
return instance
# Initializing
def __init__(self):
print("Example Instance.")
# Calling destructor
def __del__(self):
print("Destructor called, Example deleted.")
结果:
>>> obj = Example()
example created <__main__.Example object at 0x7fd0b3efa5b0>
Example Instance.
>>> del obj
Destructor called, Example deleted.
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.