阿小信大人的头像
Life is short (You need Python) Bruce Eckel

Python Borg单例模式2014-10-10 17:39

In [4]: class Borg:
   ...:     __share_state = {}
   ...:     def __init__(self):
   ...:         self.__dict__ = self.__share_state
   ...:

In [5]: b1 = Borg()

In [6]: b1.x = 1

In [7]: b2 = Borg()

In [8]: b2.x
Out[8]: 1

In [9]: b2.x = 2

In [10]: b1.x
Out[10]: 2

In [11]: b1.__dict__
Out[11]: {'x': 2}

In [12]: b2.__dict__
Out[12]: {'x': 2}

In [13]: Borg._Borg__share_state
Out[13]: {'x': 2}

In [14]: id(b1)
Out[14]: 140106795108112

In [15]: id(b2)
Out[15]: 140106795108400

In [16]: d = {}

In [17]: nd = d

In [18]: nd['a'] = 1

In [19]: nd
Out[19]: {'a': 1}

In [20]: d
Out[20]: {'a': 1}

魔法在于b1.dict、b2.dict和Borg._Borgshare_state指向的是同一个class attribute对象share_state,修改dict时也会修改share_state,在每次初始化时都会用这个class attribute对象替换更新dict__

若非特别声明,文章均为阿小信的个人笔记,转载请注明出处。文章如有侵权内容,请联系我,我会及时删除。

#Python#  
分享到:
阅读[2089]

你可能也感兴趣的文章推荐

本文最近访客

网友216.*.*.226[Seattle]2021-05-06 23:50
网友54.*.*.161[法国]2021-05-06 23:45
网友207.*.*.63[Redmond]2021-05-06 23:28
网友207.*.*.21[Redmond]2021-05-06 23:26