class singleton(type):
def __new__(cls, name, bases, dict):
old_init = dict.get('__init__')
old_new = super(cls.__class__, cls).__new__
def _wrap_init(self, *args, **kwargs):
if hasattr(self.__class__,'_onlyou_'):
return
setattr(self.__class__,'_onlyou_', self)
old_init(self,*args,**kwargs)
def _wrap_new(cls, *args, **kwargs):
if hasattr(cls,'_onlyou_'):
return getattr(cls, '_onlyou_')
return old_new(cls, *args, **kwargs)
dict['__init__'] = _wrap_init
dict['__new__'] = _wrap_new
return type.__new__(cls, name, bases, dict)
class A(object):
__metaclass__ = singleton
def __init__(self, a,b):
self.a=a
self.b=b
a=A(1,2) #first
b=A()
c=A(1,2,3,4,5)
id(a) == id(b) == id(c)
阅读(2011) | 评论(0) | 转发(0) |