Open ls0f opened 8 years ago
__new__
class Test(object): def __new__(cls, *args, **kwargs): if not hasattr(cls, "_init"): orig = super(Test, cls).__new__(cls, *args, **kwargs) cls._init = orig return cls._init a = Test() a.tt = 1111 b = Test() print b.tt
def foo(cls): ins = {} def getinstance(*args, **kwargs): if 'ins' not in ins: ins['ins'] = cls(*args, **kwargs) return ins['ins'] return getinstance @foo class Test(object): pass a = Test() a.tt = 1111 b = Test() print b.tt
使用
__new__
使用装饰器