ls0f / my-issues

0 stars 0 forks source link

Python 实现单例模式 #17

Open ls0f opened 8 years ago

ls0f commented 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