#-*-coding:utf-8-*-
'''
意图:保证一个类仅有一个实例,并提供一个访问它的全局访问点
'''
class Singleton(type):
def __init__(cls, name, bases, dict): #使得不能实例化
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls, *args, **kw): #引用类时返回实例
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
class MyClass(object):
__metaclass__ = Singleton
def printA4(self):
print 'this A4'
if __name__ == "__main__":
c1 = MyClass()
c2 = MyClass()
# if c1 is c2:
if id(c1) is id(c2):
print 'Same'
else:
print 'Different'
c1.printA4()