您的位置:首页 > 编程语言 > Python开发

Python - 单例模式(Singleton)(转)

2016-09-04 14:01 603 查看
单例模式(Singleton)

原文地址

单例模式, 类的实例从始至终, 只被创建一次, 这些类可以用来管理一些资源;

需要继承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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python singleton 单例