python单例_Python - 单例模式(Singleton)
生活随笔
收集整理的這篇文章主要介紹了
python单例_Python - 单例模式(Singleton)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
單例模式(Singleton)
本文地址:?http://blog.csdn.net/caroline_wendy/article/details/23374575
單例模式
, 類的實例從始至終, 只
被創(chuàng)建一次
, 這些類可以用來管理一些資源;
需要 繼承Object類
, 才可以使用類的方法 super()
, 只實例化一次;
參見Python文檔: Note super() only works for new-style classes.
代碼:
# -*- coding: utf-8 -*-
#eclipse pydev, python 2,7
#by C.L.Wang
class Singleton(object):
g = None
def __new__(cls):
if '_inst' not in vars(cls):
cls._inst = super(Singleton, cls).__new__(cls)
print 'new'
return cls._inst
def __init__(self):
print id(self)
if __name__ == '__main__':
a = Singleton()
a.g=1
b = Singleton()
print b.g
輸出:
new
27969200
27969200
1
總結(jié)
以上是生活随笔為你收集整理的python单例_Python - 单例模式(Singleton)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: cmd oracle 连接实例_C#连接
- 下一篇: jupyter中保存图片_露哥的摸爬滚打