iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python 单例模式
  • 305
分享到

python 单例模式

模式python 2023-01-30 22:01:31 305人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

单例模式 多次实例化的结果指向同一个实例   单例模式实现方式 方式一: 1 import settings 2 3 class Mysql: 4 __instance = None 5 6 def __

单例模式

多次实例化的结果指向同一个实例

 

单例模式实现方式

方式一:

 1 import settings
 2 
 3 class Mysql:
 4     __instance = None
 5 
 6     def __init__(self, ip, port):
 7         self.ip = ip
 8         self.port = port
 9 
10     @claSSMethod
11     def from_conf(cls):
12         if cls.__instance is None:
13             cls.__instance = cls(settings.IP,settings.PORT)
14         return cls.__instance
15 
16 obj1 = mysql.from_conf()
17 obj2 = Mysql.from_conf()
18 obj3 = MySQL.from_conf()
19 print(obj1)
20 print(obj2)
21 print(obj3)

 

方式二:

 1 import settings
 2 
 3 def singleton(cls):
 4     _instance = cls(settings.IP, settings.PORT)
 5 
 6     def wrapper(*args, **kwargs):
 7         if args or kwargs:
 8             obj = cls(*args, **kwargs)
 9             return obj
10         return _instance
11 
12     return wrapper
13 
14 @singleton
15 class MySQL:
16     def __init__(self, ip, port):
17         self.ip = ip
18         self.port = port
19 
20 obj1 = MySQL()
21 obj2 = MySQL()
22 obj3 = MySQL()
23 print(obj1)
24 print(obj2)
25 print(obj3)

 

 

方式三:

 1 import settings
 2 
 3 class Mymeta(type):
 4     def __init__(self, class_name, class_bases, class_dic):
 5         self.__instance = self(settings.IP, settings.PORT)
 6 
 7     def __call__(self, *args, **kwargs):
 8         if args or kwargs:
 9             obj = self.__new__(self)
10             self.__init__(obj, *args, **kwargs)
11             return obj
12         else:
13             return self.__instance
14 
15 class MySQL(metaclass=Mymeta):
16     def __init__(self, ip, port):
17         self.ip = ip
18         self.port = port
19 
20 obj1 = MySQL()
21 obj2 = MySQL()
22 obj3 = MySQL()
23 print(obj1)
24 print(obj2)
25 print(obj3)

 

 

方式四:

 1 def f1():
 2     from singleton import instance
 3     print(instance)
 4 
 5 def f2():
 6     from singleton import instance,MySQL
 7     print(instance)
 8     obj = MySQL('1.1.1.1', '3389')
 9     print(obj)
10 
11 f1()
12 f2()
13 
14 
15 singleton.py文件里内容:
16 import settings
17 
18 class MySQL:
19     print('run...')
20 
21     def __init__(self, ip, port):
22         self.ip = ip
23         self.port = port
24 
25 instance = MySQL(settings.IP, settings.PORT)

 

--结束END--

本文标题: python 单例模式

本文链接: https://www.lsjlt.com/news/179402.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作