1

Source: Python and the Singleton Pattern

According to most upvoted comment in the top answer init gets called multiple times if new returns class instance.

So I checked this:

class Singleton(object):

    _instance = None

    def __new__(cls, *args, **kwargs):
        print 'Singleton.__new__ called with class', cls
        if not cls._instance:
            cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
        return cls._instance


class Cache(Singleton):

    def __init__(self, size=100):
        print 'I am called with size', size


class S(Singleton):
    def __init__(self, param):
        print 'I am S with param', param


c = Cache(20)
s = S(10)

Result:

Singleton.__new__ called with class <class '__main__.Cache'>
I am called with size 20
Singleton.__new__ called with class <class '__main__.S'>
I am S with param 10

Apparently init does not called more than once in a class inheriting from Singleton. Has smth changed in Python that handles this in the meantime (considering the question was asked in 2008), or am I missing smth here?

Community
  • 1
  • 1
LetMeSOThat4U
  • 6,470
  • 10
  • 53
  • 93

2 Answers2

0

Please replace your two last lines with

for x in range(5):
    c = Cache(x)
    s = S(x)

and post the result.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
  • Now I get it, I thought they were talking about some inheritance magic and did not think of a simple thing.. Anyway pls take a look at http://stackoverflow.com/questions/18386562/python-singleton-take-2 too – LetMeSOThat4U Aug 22 '13 at 16:56
0

From the print result it is obvious that __init__ is called upon construction of each new Cache and S object.

When you create an instance of a class (eg Cache(10)) Python first creates a new instance of it using __new__ then initializes it using __init__.

In other words apparently you misread something.

Sheena
  • 15,590
  • 14
  • 75
  • 113