python单例模式数据库连接池_Python实现单例模式的四种方式
生活随笔
收集整理的這篇文章主要介紹了
python单例模式数据库连接池_Python实现单例模式的四种方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
# 單例模式實現方式一:類方法import settings?class MySQL:__instance=Nonedef __init__(self, ip, port):self.ip = ipself.port = port?@classmethoddef from_conf(cls):if cls.__instance is None:cls.__instance=cls(settings.IP, settings.PORT)return cls.__instanceobj1=MySQL.from_conf()obj2=MySQL.from_conf()obj3=MySQL.from_conf()# obj4=MySQL('1.1.1.3',3302)print(obj1)print(obj2)print(obj3)# print(obj4)?# 單例模式實現方式二:裝飾器import settings?def singleton(cls):_instance=cls(settings.IP,settings.PORT)def wrapper(*args,**kwargs):if len(args) !=0 or len(kwargs) !=0:obj=cls(*args,**kwargs)return objreturn _instancereturn wrapper?@singleton #MySQL=singleton(MySQL) #MySQL=wrapperclass MySQL:def __init__(self, ip, port):self.ip = ipself.port = port?obj1=MySQL() obj2=MySQL() obj3=MySQL() obj4=MySQL('1.1.1.3',3302) print(obj1)print(obj2)print(obj3)print(obj4)?# 單例模式實現方式三:通過元類:import settings?class Mymeta(type):def __init__(self,class_name,class_bases,class_dic):#self=MySQL這個類self.__instance=self(settings.IP,settings.PORT)?def __call__(self, *args, **kwargs):# self=MySQL這個類if len(args) != 0 or len(kwargs) != 0:obj=self.__new__(self)self.__init__(obj,*args, **kwargs)return objelse:return self.__instance?class MySQL(metaclass=Mymeta): #MySQL=Mymeta(...)def __init__(self, ip, port):self.ip = ipself.port = port??obj1=MySQL()obj2=MySQL()obj3=MySQL()obj4=MySQL('1.1.1.3',3302)print(obj1)print(obj2)print(obj3)print(obj4)# 單例模式實現方式四:模塊導入:def f1():from singleton import instanceprint(instance)?def f2():from singleton import instance,MySQLprint(instance)obj=MySQL('1.1.1.3',3302)print(obj)?f1()f2()
同步發布在小猿取經博客
小猿取經 - 博客園?www.cnblogs.com總結
以上是生活随笔為你收集整理的python单例模式数据库连接池_Python实现单例模式的四种方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 机器人聊天软件c#_使用python3.
- 下一篇: ora-24811提供写入的数据少于指定