Python singleton, take 2

怎甘沉沦 提交于 2020-01-05 08:35:12

问题


Read this first pls: does __init__ get called multiple times with this implementation of Singleton? (Python)

class Singleton(object):

    _instance = None

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


class Cache(Singleton):

    def __init__(self, size=100):
        print 'Cache.__init__ called with size', size



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

Result:

Singleton.__new__ called with class <class '__main__.Cache'>
Singleton.__new__ creating instance of class <class '__main__.Cache'>
Cache.__init__ called with size 0
Singleton.__new__ called with class <class '__main__.Cache'>
Singleton.__new__ called with class <class '__main__.Cache'>
Singleton.__new__ called with class <class '__main__.Cache'>
Singleton.__new__ called with class <class '__main__.Cache'>

It seems to work now, but the question is whether calling inhering class init explicitly in Singleton is pythonic? Is there smth that might go wrong with this?


回答1:


Doesn't work. You never actually return anything from __new__, so it returns the default value of None. cls._instance is set properly, but you don't get cls._instance when you call Cache.



来源:https://stackoverflow.com/questions/18386562/python-singleton-take-2

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