gpt4 book ai didi

python - 尝试打印时实例对象被删除

转载 作者:太空宇宙 更新时间:2023-11-03 10:59:33 25 4
gpt4 key购买 nike

我正在尝试重载 new,这是我的尝试:-

class String(object):
def __new__(cls, *args, **kargs):
print "in __new__"
return super(String, cls).__new__(cls)
def __init__(self):
print "Initiating instance of String"
raise Exception
def __del__(self):
print "Deleting instance of String"

我在许多地方读到实际上 __new__ 创建实例,而 __init__ 只是初始化实例。我故意在 __init__ 中抛出异常以让它失败。这里对 new 的调用返回了实例,但是 init 失败了,所以我期待一个没有任何属性的实例。但结果让我大吃一惊——

st = String()
in __new__
Initiating instance of String

Traceback (most recent call last):
File "<pyshell#89>", line 1, in <module>
st = String()
File "<pyshell#88>", line 7, in __init__
raise Exception

正如预期的那样,它在 __init__ 中失败了,接下来我尝试打印新创建的实例 'st' 结果令我惊讶,它在打印之前删除了实例。

>>> print st
**Deleting instance of String**

Traceback (most recent call last):
File "<pyshell#90>", line 1, in <module>
print st
NameError: name 'st' is not defined

请帮助我理解这种奇怪的行为。

注意 - 我知道什么时候应该重载 __new__ 什么时候不应该。

最佳答案

在 Python 设法将内存中的对象分配给变量名之前引发了异常。因此内存中对象的引用计数器0,所以它得到了“垃圾收集”,你得到了name is not defined异常。

评论更新:如果阈值已满,Python 会在尝试为新对象分配内存时运行 GC。在您的情况下,它可能是达到了第 0 代的阈值,因为它是新的“失败” String 对象应该存在的地方。触发 GC 的事件本身是内存分配以执行 print

关于python - 尝试打印时实例对象被删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35527720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com