如果是在python2中,就需要手动继承object,
基于__new__方法
基于__new__方法 class Foo(object): def __new__(cls,*args,**kwargs): if not hasattr(cls,'_instance'): cls._instance=super(Foo,cls).__new__(cls,*args,**kwargs) return cls._instance
基于装饰器方法
def foo(cls,*args,**kwargs): dic={} def _foo(): if cls not in dic: dic[cls]=cls(*args,**kwargs) return dic[cls] return _foo @foo class MyClass(object): x=2 def __init__(self,x=1) self.x=x
基于元类metaclass实现
class Singleton(type): def __init__(cls,*args,**kwargs): super(Singleton,cls).__init__(name,bases,dict) cls._instance=None def __call__(cls,*args,**kwargs): if cls._instance is None: cls._instance=super(Singleton,cls).__call__(*args,**kwargs) return cls._instance
# 在python2中: class MyClass(object): __metaclass__=Singleton
# 在python3中
class Myclass(metaclass=Singleton):
pass
知识点总结,封装,静态变量变成私有变量