1

请先阅读这篇文章:__init__ 是否会在 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)

结果:

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'>

它现在似乎可以工作,但问题是在 Singleton 中显式调用继承类init是否是 Pythonic?这有什么可能出错的吗?

4

1 回答 1

0

不工作。您实际上从未从 中返回任何内容__new__,因此它返回 的默认值None。设置正确,但调用时cls._instance没有得到。cls._instanceCache

于 2013-08-22T16:57:45.950 回答