python 单例模式的实现方法_python中单例模式的四种实现方式
配置文件settings.py
IP='100.0.0.2'
PORT=3302
方式一:綁定給類的方法
class Mysql:
__instance = None
def __init__(self, ip, port):
self.ip = ip
self.port = port
@classmethod
def from_conf(cls):
if cls.__instance is None:
cls.__instance = cls(settings.IP, settings.PORT)
return cls.__instance
obj1 = Mysql.from_conf()
obj2 = Mysql.from_conf()
obj3 = Mysql.from_conf()
obj = Mysql('1.1.1.0', 3302)
print(obj)
print(obj1)
print(obj2)
print(obj3)
方式二:裝飾器
def singleton(cls):
# 先造好一個空對象
instance = cls(settings.IP, settings.PORT)
def wrapper(*args, **kwargs):
if args or kwargs: # args 和 kwargs 有值時,返回obj
obj = cls(*args, **kwargs)
return obj
return instance
return wrapper
@singleton
class Mysql: # Mysql = singleton(Mysql)
def __init__(self, ip, port):
self.ip = ip
self.port = port
obj1 = Mysql() # wrapper()
obj2 = Mysql()
obj3 = Mysql()
obj4 = Mysql('1.1.1.2', 3303)
print(obj1)
print(obj2)
print(obj3)
print(obj4)
方式三:自定義元類
class Mymeta(type):
def __init__(self, class_name, class_base, class_dic):
# 先造好一個空對象
self.instance = self(settings.IP, settings.PORT)
def __call__(self, *args, **kwargs):
if args or kwargs:
# 拿到一個空對象
obj = self.__new__(self)
# 執行__init__方法為對象初始化屬性
self.__init__(obj, *args, **kwargs)
# 返回一個實例化好的對象
return obj
return self.instance
class Mysql(metaclass=Mymeta):
def __init__(self, ip, port):
self.ip = ip
self.port = port
obj1 = Mysql() # 調用Mysql就是調用__call__方法
obj2 = Mysql()
obj3 = Mysql()
obj4 = Mysql('1.1.1.4', 3301)
print(obj1)
print(obj2)
print(obj3)
print(obj4)
方式四:利用模塊的導入特性
importsettingsclassMysql:def __init__(self, ip, port):
self.ip=ip
self.port=port
instance= Mysql(settings.IP,settings.PORT)
singleton.py
def f1():
from singleton import instance
print(instance)
def f2():
from singleton import instance, Mysql
print(instance)
obj = Mysql('1.1.1.0', 3303)
print(obj)
f1()
f2()
總結
以上是生活随笔為你收集整理的python 单例模式的实现方法_python中单例模式的四种实现方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 无法跳转 vscode_爱了爱了,这个V
- 下一篇: badboy录制乱码_Badboy 录制