user3282758
user3282758

Reputation: 1471

strange behavior of __new__ in python

While reading about __new__, I came across an example on StackOverflow itself. As I was working on that example, I modified the code slightly. The modified code is as follows:

class A1(object):
    def __new__(cls):
        print 'in new'
    def __init__(self):
        print 'in init'

a = 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 is as follows:

in new
NEW
INIT

EXISTS
INIT

EXISTS
INIT

That is, when instance is created for class 'A1', only __new__ is executed, whereas for class 'A' instances both __new__ and __init__ are being executed.

I am not able to figure out the reason for this.

Upvotes: 1

Views: 90

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121654

You did not return a new instance in your first example; you need to return an instance for __init__ to be called on.

The following calls both the __new__ and __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 at 0x106e5d090>

Upvotes: 5

Related Questions