python 单例模式

Posted hades0607

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 单例模式相关的知识,希望对你有一定的参考价值。

单例模式

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

 

单例模式实现方式

方式一:

 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)

 

以上是关于python 单例模式的主要内容,如果未能解决你的问题,请参考以下文章

Python 单例设计模式

Python单例

一日一技:Python 下面最简单的单例模式写法

Python面向对象之单例模式

常用代码片段

常用代码片段