资源: Python 和单例模式
根据最佳答案中最受好评的评论,如果是新的, init会被多次调用返回类实例,则会
所以我检查了这个:
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)
结果:
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
显然init在继承自 Singleton 的类中不会多次调用。同时处理这个问题的 Python 中的 smth 是否发生了变化(考虑到 2008 年提出的问题),还是我在这里错过了 smth?