H****S 发帖数: 1359 | 1 很简单,写一个Python Singleton Class。
类似于这样的不算,
class foo(object):
_instance = None
@classmethod
def get_instance(cls, *args, **kargs):
if cls._instance is None:
cls._instance = foo(*args, **kargs)
return cls._instance
...
因为用户还是可以直接调用foo(*args, **kargs)来创建新的object,而Python是没
有private/protected这样的access modifier的。
我的答案,
class foo(object):
_instance = None
def _initialize(self, *args, **kargs):
# do your initialization here
def __new__(cls, *args, **kargs):
if cls._instance is None:
cls._instance = super(foo, cls).__new__(*args, **kargs)
cls._instance._initialize(*args, **kargs)
return cls._instance | j*****k 发帖数: 1198 | 2 using class decorator.
【在 H****S 的大作中提到】 : 很简单,写一个Python Singleton Class。 : 类似于这样的不算, : class foo(object): : _instance = None : @classmethod : def get_instance(cls, *args, **kargs): : if cls._instance is None: : cls._instance = foo(*args, **kargs) : return cls._instance : ...
|
|