我正在努力创建一个像博格一样的课程。我希望所有实例共享一个特定的属性,但我希望其他属性对于实例是唯一的。以下是我到目前为止的情况:
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)
答案 0 :(得分:6)
这就是我要做的事情:
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
我希望您知道如何将此示例用于您自己的目的。我不太确定你的代码是什么,所以我没有猜测并写了一个最小的例子。