Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (1.6k points)

I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern.

However, I'm a bit confused as to why __init__ is always called after __new__. I wasn't expecting this. Can anyone tell me why this is happening and how I can implement this functionality otherwise? (Apart from putting the implementation into the __new__ which feels quite hacky.)

Here's an example:

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()

Outputs:

NEW

INIT

EXISTS

INIT

EXISTS

INIT

Why?

1 Answer

0 votes
by (25.1k points)

Since the __new__ function is called when creating the instance and __init__ is called when initializing the instance and these two steps happen in this order only, so the __new__ function is always called first and __init__ function is called after that.

Related questions

+1 vote
1 answer
0 votes
1 answer
asked Sep 30, 2019 in Python by Sammy (47.6k points)
0 votes
2 answers

Browse Categories

...