I'm trying to reload new, and this is my attempt: -
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"
I read in many places that actually __new__create an instance, and __init__it's just initializing the instance. I deliberately throw an exception at __init__to prevent it from happening. Here the call newreturns an instance, but initfails, so I expect an instance that will not have any attributes. But the result surprised me somehow -
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
As expected, this did not succeed in __init__, then I tried to print the newly created instance 'st', and the result surprised me, it deleted the instance before printing.
>>> 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
Please help me understand this strange behavior.
. , __new__, .