其他分享
首页 > 其他分享> > 使用元类实现单例模式

使用元类实现单例模式

作者:互联网

class MyType(type):
    def __init__(cls, *args, **kwargs):
        cls.instance = None
        super(MyType, cls).__init__(*args, **kwargs)

    def __new__(mcs, *args, **kwargs):
        return super(MyType, mcs).__new__(mcs, *args, **kwargs)

    def __call__(cls, *args, **kwargs):
        if not cls.instance:
            cls.instance = cls.__new__(cls, *args, **kwargs)
            cls.__init__(cls.instance, *args, **kwargs)
        return cls.instance


class Foo(metaclass=MyType):
    pass

标签:__,args,模式,元类,instance,单例,kwargs,MyType,cls
来源: https://www.cnblogs.com/miracleeeeeeee/p/16061734.html