Python Singletion
单例模式:
class SingleModel(object):
def __new__(cls,*args,**kwargs):
if not hasattr(cls, '_isinstance'):
orig = super(SingleModel,cls)
cls._isinstance = orig.__new__(cls,*args,**kwargs)
return cls._isinstance
1.文件导入的形式(常用)
s1.py
class Foo(object):
def test(self)
print(123)
v = Foo()
s2.py
from s1 import v as v1
print(v1,id(v1))
from s1 import v as v2
print(v2,id(v2))
2.基于类实现的形式:
class Singleton(object):
def __init__(self):
import timt
timt.sleep(2)
@classmethon
def instance(cls, *args, **kwargs):
if not hasattr(Singleton,'_instance'):
Singleton._instance = Singleton(*args, **kwargs)
return Singleton._instance
obj1 = Singleton.instance()
obj2 = Singleton.instance()
3.基于类的构造方法__new__的形式:
import threading
class Singleton(object):
_instance_lock = threading.Lock()
def __init__(self):
pass
def __new__(cls, *args, **kwargs): #类名加括号执行__new__方法,对象加括号执行__call__方法
if not hasattr(Singleton, "_instance"):
with Singleton._instance_lock: #为了线程安全,加锁
if not hasattr(Singleton, "_instance"): #有点不解,为什么要在重复一遍
Singleton._instance = object.__new__(cls)
return Singleton._instance
obj1 = Singleton()
obj2 = Singleton()
4.基于metaclass(元类)的形式:
import threading
class SingletonType(type):
_instance_lock = threading.Lock()
def __call__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
with SingletonType._instance_lock:
if not hasattr(cls, '_instance'):
cls._instance = super(SingletonType,cls).__call__(*args, **kwargs)
return cls._instance
class Foo(metaclass=SingletonType):
def __init__(self,name)
obj1 = Foo('mihon')
obj2 = Foo('allon')
5.元信息类的补充
class MyType(type):
def __init__(self,*args,**kwargs):
print('type_init')
super(MyType,self).__init__(*args,**kwargs)
def __call__(self,*args,**kwargs):
print('type_call')
super.(MyType,self).__call__(*args,**kwargs)
class Foo(metaclass=MyType):
def __init__(self,name):
self.name = name
class Bar(Foo):
def __init__():
pass
def __call__():
pass
obj = Bar()
会执行:两次'type_init',一次'type_call'
Foo = type('Foo',(MyType,),{})
class Bar(Foo)
pass
class Foo(MyType('Foo',(object,),{}))
def with_metaclass(arg,base):
print('类对象',MyType('Foo', (base,), {}))
return arg('Foo',(base,), {})
class Foo(with_metaclass(MyType,object))
user = 'mihon'
age = 18

浙公网安备 33010602011771号