Python singleton, take 2

2019-08-10 20:03发布

问题:

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.