单例模式(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