python 面试相关
2014-06-03 16:09
441 查看
python单例模式:
Python真的需要单例模式吗?我指像其他编程语言中的单例模式。
答案是:不需要! 因为,Python有模块(module),最pythonic的单例典范。模块在在一个应用程序中只有一份,它本身就是单例的,将你所需要的属性和方法,直接暴露在模块中变成模块的全局变量和方法即可
Python真的需要单例模式吗?我指像其他编程语言中的单例模式。
答案是:不需要! 因为,Python有模块(module),最pythonic的单例典范。模块在在一个应用程序中只有一份,它本身就是单例的,将你所需要的属性和方法,直接暴露在模块中变成模块的全局变量和方法即可
#!/usr/bin/env python #encoding=utf-8 import threading #单例类 class Singleton(object): instance = None mutex =threading.Lock() def __init__(self): pass @ staticmethod #声明这个是静态方法 def GetInstance(): if(Singleton.instance == None): Singleton.mutex.acquire() if(Singleton.instance == None): print "init the instance" Singleton.instance = Singleton() else: print "init the instance already" Singleton.mutex.release() else: print "init the instance already" return Singleton.instance if __name__ == '__main__': Singleton.GetInstance() Singleton.GetInstance() Singleton.GetInstance() #类只能调用到静态的方法,切记
相关文章推荐
- python及其相关面试
- 《面试》---Python 实现二叉树结构以及相关遍历
- Python面试相关
- python面试相关
- 面试笔试系列之三 字符串相关
- 嵌入式或LINUX相关研发面试题目
- Python计时相关操作详解【time,datetime】
- python资料相关网址
- 收集整理的Python 相关的书籍信息
- 总结,面试相关的问题的回答技巧?(来源于天涯论坛)
- Python相关资源
- 一个python相关的BLOG
- 英语面试相关的问题
- Python的字符串编码相关小结
- 面试相关-非技术问题
- Python GUI编程-了解相关技术
- 嵌入式或LINUX相关研发面试题目
- 面试相关
- python cgi设计相关的网址
- 嵌入式与linux相关研发面试题目(转)