strange behavior of __new__ in python -
while reading __new__, came across example on stackoverflow itself. working on example, modified code slightly. modified code follows:
class a1(object): def __new__(cls): print 'in new' def __init__(self): print 'in init' = a1() class a(object): _dict = dict() def __new__(cls): if 'key' in a._dict: print "exists" return a._dict['key'] else: print "new" return super(a, cls).__new__(cls) def __init__(self): print "init" a._dict['key'] = self print "" a1 = a() a2 = a() a3 = a()
the output follows:
in new new init exists init exists init
that is, when instance created class 'a1', __new__ executed, whereas class 'a' instances both __new__ , __init__ being executed.
i not able figure out reason this.
you did not return new instance in first example; need return instance __init__
called on.
the following calls both __new__
, __init__
methods:
class a1(object) : def __new__(cls) : print 'in new' return super(a1, cls).__new__(cls) def __init__(self) : print 'in init'
demo:
>>> class a1(object) : ... def __new__(cls) : ... print 'in new' ... return super(a1, cls).__new__(cls) ... def __init__(self) : ... print 'in init' ... >>> a1() in new in init <__main__.a1 object @ 0x106e5d090>
Comments
Post a Comment