元类实现单例模式

# -*- coding:utf-8 -*-


class Singleton(type):
    """
    单例模式

    e.g.
    
    #Python2
    class MyClass(BaseClass):
        __metaclass__ = Singleton

    #Python3
    class MyClass(BaseClass, metaclass=Singleton):
        pass
    """

    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

你可能感兴趣的:(Python常用模块,设计模式,python)