does __init__ get called multiple times with this implementation of Singleton? (Python)

与世无争的帅哥 提交于 2019-12-11 11:15:18

问题


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?


回答1:


Please replace your two last lines with

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

and post the result.




回答2:


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.



来源:https://stackoverflow.com/questions/18383970/does-init-get-called-multiple-times-with-this-implementation-of-singleton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!