Python 实现单例模式

简介:

Python 实现单例模式

    

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# 使用Python实现单例模式
 
# 方法一: 使用__new__方法
class  SingleTon( object ):
     def  __new__( cls * args,  * * kwargs):
         if  not  hasattr ( cls '_instance' ):
             cls ._instance  =  object .__new__( cls * args,  * * kwargs)
         return  cls ._instance
 
 
class  TestClass(SingleTon):
     =  1
 
 
# 方法二: 使用装饰器(decorator)
def  SingleTon1( cls * args,  * * kwargs):
     instances  =  {}
     def  _singleTon():
         if  cls  not  in  instances:
             instances[ cls =  cls ( * args,  * * kwargs)
         return   instances[ cls ]
     return  _singleTon
 
 
@SingleTon1
class  TestClass1( object ):
     =  1
 
 
 
# 共享属性  属性是共享的,但是并非单例模式
class  SingleTon3( object ):
     _state  =  {}
     def  __new__( cls * args,  * * kwargs):
         obj  =  object .__new__( cls * args,  * * kwargs)
         obj.__dict__  =  cls ._state
         return  obj
 
 
class  TestClass3(SingleTon3):
     =  1
 
test1  =  TestClass3()
test2  =  TestClass3()
test1.a  =  2
print (test1.a)
print (test2.a)
print (test1)
print (test2)



本文转自 许大树 51CTO博客,原文链接:http://blog.51cto.com/abelxu/1967293,如需转载请自行联系原作者
相关文章
|
4月前
|
Python
|
3月前
|
存储 安全 Python
如何在Python中实现一个单例模式,确保在多线程环境中也是安全的?
【2月更文挑战第5天】【2月更文挑战第11篇】如何在Python中实现一个单例模式,确保在多线程环境中也是安全的?
|
4月前
|
存储 安全 Python
|
6月前
|
Python
62 python - 单例模式
62 python - 单例模式
18 0
|
8月前
|
缓存 安全 开发者
Python 单例模式讲解和代码示例
Python 单例模式讲解和代码示例
29 0
Python print() 打印两个 list ,实现中间换行
Python print() 打印两个 list ,实现中间换行
|
Python
Python实现因子分析(附案例实战)
Python实现因子分析(附案例实战)
1105 0
Python实现因子分析(附案例实战)
|
10月前
|
设计模式 搜索推荐 开发者
Python单例模式(Singleton)的N种实现
单例模式保证了在程序的不同位置都可以且仅可以取到同一个对象实例:如果实例不存在,会创建一个实例;如果已存在就会返回这个实例。因为单例是一个类,所以你也可以为其提供相应的操作方法,以便于对这个实例进行管理。
|
12月前
|
设计模式 数据库连接 数据库
一日一技:Python 下面最简单的单例模式写法
一日一技:Python 下面最简单的单例模式写法
73 0
|
Python
Python 基于python实现单例模式
Python 基于python实现单例模式
50 0