#!/usr/bin/env python
#coding:utf-8

class Borg(object):
    _share_state = {}
    def __init__ (self):
        '''
        将__dict__和_share_state指向了同一个地址
        这样会使_share_state的内容始终保持与__dict__同步
        由于_share_state是类变量,最终就可以实现多个实例的__dict__保持同步的效果
        '''
        self.__dict__ = self._share_state

class Singleton(Borg):
    def __init__ (self, *args, **kwargs):
        super(Singleton, self).__init__()
        self.val = args[0]
    def __str__ (self):
        return self.val

x = Singleton('test1')
y = Singleton('test2')
z = Singleton('test3')

print x #test3
print y #test3
print z #test3

 本文涉及的知识点:

1、__dict__

2、类变量

3、super

4、__str__

5、Python赋值的原理

 

相关文章:

  • 2021-06-01
  • 2021-09-18
  • 2022-12-23
  • 2021-11-21
  • 2022-12-23
  • 2022-03-04
  • 2021-10-29
猜你喜欢
  • 2021-10-03
  • 2021-08-10
  • 2022-01-16
  • 2021-04-21
  • 2021-12-10
  • 2021-11-21
相关资源
相似解决方案