我正在尝试超载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__
以使其失败。在这里调用tonew
返回实例但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
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句