多次被称为驱动器
我正在尝试检查 new , init 和 del 的作品,并在下面提到的代码下运行,引起我注意的是destructor被称为两次而且我不知道它的确切原因,有人可以帮忙吗?
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
i am trying to check how new , init and del works and was running below mentioned code , what caught my attention is destructor is being called twice and i don't know the exact reason of it, Can anyone help with it?
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自Geeksforgeeks:
Python使用参考计数和垃圾收集器自动为您管理内存。也就是说,不必要的参考文献被自动删除。
因此,您需要明确创建它以避免这种行为。
结果:
From geeksforgeeks:
Python automatically manages memory for you using reference counting and garbage collector. That is, references unnecessary are being automatically deleted.
So you need to create it explicitly to avoid this behavior.
result: