#_*_ encoding: utf-8 _*_ @author: ty hery 2019/9/6
# 共享属性:创建实例时把所有实例的__dict__指向同一个字典,这样它们具有相同的属性和方法.
class Borg(object):
_state = {}
def __new__(cls, *args, **kw):
ob = super(Borg, cls).__new__(cls, *args, **kw)
ob.__dict__ = cls._state
return ob
class MyClass2(Borg):
a = 1
b1 = MyClass2()
b2 = MyClass2()
b3 = MyClass2()
b1.a='萨菲的'
b2.a='萨菲02'
b1.a='萨菲03'
MyClass2.a = 333
print(id(b1),id(b2),id(b3))
print(b1.a,b2.a,b3.a)
输出:
42770952 42771008 42770616
萨菲03 萨菲03 萨菲03
167529720 167529720 167529720
# 装饰器版本
def singleton(cls, *args, **kw):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instances[cls]
return getinstance
@singleton
class MyClass:
a = 1
b1 = MyClass()
b2 = MyClass()
b3 = MyClass()
b1.a= 11
b2.a= 12
b3.a= 13
print(id(b1),id(b2),id(b3))
print(b1.a,b2.a,b3.a)
输出:42516376 42516376 42516376
13 13 13