python - 创建一个有点像博格的类

标签 python design-patterns

我正在尝试制作一个类似博格的类(class)。我希望所有实例共享一个特定的属性,但我希望实例独有其他属性。这是我目前所拥有的:

class SharedFacility:
  _facility = None

  def __init__(self):
    entries = {'facility': self._facility}
    self.__dict__.update(entries) 

  def _getfacility(self):
    return self._facility

  def _setfacility(self, value):
    self._facility = value

  facility = property(_getfacility, _setfacility)


class Warning(SharedFacility):
  def __init__(self, warnlevel, warntext):
    SharedFacility.__init__(self)
    print "Warning.__init__()"
    self.warntext = warntext
    self.warnlevel = warnlevel

  def __call__(self):
    self.facility(self.warnlevel, self.warntext)


def functionOne(a,b):
  print 'functionOne: a=%s, b=%s' % (a,b)

def functionTwo(a,b):
  print 'functionTwo: a=%s, b=%s' % (a,b)

####################################################
w1 = Warning(1, 'something bad happened')
w1.facility = functionOne
w2 = Warning(5, 'something else bad happened')
import pdb; pdb.set_trace()

if w1.facility is w2.facility:
  print "They match!"

w1() # functionOne: a=1, b='something bad happened'
w2() # functionOne: a=5, b='something else bad happened'

w2.facility = functionTwo
if w1.facility is w2.facility:
  print "They match!"

w1() # functionTwo: a=1, b='something bad happened'
w2() # functionTwo: a=5, b='something else bad happened'

上面的代码不起作用。我希望 w1.facility 和 w2.facility 是对同一对象的引用,但 w1.warntext 和 w2.warntext 是两个不同的值。我正在使用 python 2.4.3(没有意义提到我升级,因为我不能)。

解决方案:

class Warning(object):
  _facility = None

  def __init__(self, warnlevel, warntext):
    print "Warning.__init__()"
    self._warntext = warntext
    self._warnlevel = warnlevel

  def __call__(self):
    Warning._facility(self._warnlevel, self._warntext)

  def _getfacility(self):
    return Warning._facility

  def _setfacility(self, value):
    Warning._facility = value

  facility = property(_getfacility, _setfacility)

@staticmethod
def functionOne(a,b):
  print 'functionOne: a=%s, b=%s' % (a,b)

@staticmethod
def functionTwo(a,b):
  print 'functionTwo: a=%s, b=%s' % (a,b)

最佳答案

这是我会做的:

class BorgLike:
    _shared = 'default'
    def __init__(self, unique):
        self.unique = unique
    @property
    def shared(self):
        return BorgLike._shared
    @shared.setter
    def shared(self, value):
        BorgLike._shared = value

我希望您知道如何将此示例用于您自己的目的。我不太确定您的代码需要什么,所以我避免猜测并写了一个最小的示例。

关于python - 创建一个有点像博格的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10323582/

相关文章:

c# - 如何将接口(interface)与实现分离

python - 从方法中确定定义类

design-patterns - 编程范式实用指南?

java - 事后实现接口(interface)

python - 将 Pandas Dataframe 转换为自定义嵌套 JSON

java - 我可以应用哪些模式来避免方法重载此类中的所有方法?

database - 多态 ORM 数据库模式

python - 在 airgapped 环境中安装 nltk 数据

python - 'super' 对象在 python3 中没有属性 '__getattr__'

Python 浏览器启动