单例模式
基于classmethod
class Mysql(object):
_instance = None
def __init__(self,host,port):
self.host = host
self.port = port
@classmethod
def singleton(cls):
if not cls._instance:
cls._instance = cls('127.0.0.1',8080)
return cls._instance
obj1 = Mysql.singleton()
obj2 = Mysql.singleton()
obj3 = Mysql('192.168.11.11',8080)
print(id(obj1),id(obj2),id(obj3))
基于装饰器
def singelton(cls):
_instance = cls('127.0.0.1',8080)
def inner(*args,**kwargs):
if args or kwargs:
obj = cls(*args,**kwargs)
return obj
return _instance
return inner
@singelton # Mysql = singleton(Mysql)
class Mysql(object):
def __init__(self,host,port):
self.host = host
self.port = port
obj = Mysql()
obj1 = Mysql()
obj2 = Mysql('127.0.0.1',5000)
print(id(obj),id(obj1),id(obj2))
基于元类__call__
class MymetaClass(type):
def __call__(self, *args, **kwargs):
if not getattr(self,'_instance'):
self._instance = super().__call__(*args,**kwargs)
return self._instance
class Mysql(object,metaclass=MymetaClass):
_instance = None
def __init__(self,host,port):
self.host = host
self.port = port
obj1 = Mysql('127.0.0.1',8080)
obj2 = Mysql('127.0.0.1',8000)
print(id(obj1),id(obj2))
基于__new__
class Mysql(object):
_instance = None
def __init__(self,name):
self.name = name
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = object.__new__(cls)
return cls._instance
obj1 = Mysql('jason')
obj2 = Mysql('egon')
obj3 = Mysql('kevin')
print(id(obj1),id(obj2))
print(obj1.name)
print(obj2.name)
基于模块的
from m import settings
print(id(settings))
from m import settings
print(id(settings))
from m import settings
from m1 import func
print(id(settings))
func()
附加
class Demo(object):
pass
# 类只要加括号就会新创建一个对象 无论参数是否相同 单例模式排除在外
obj1 = Demo()
obj2 = Demo()
print(id(obj1),id(obj2))