2012-04-25 1 views
3

私はborgのようなクラスを作ろうとしています。 1つの特定のプロパティをすべてのインスタンスで共有したいと思いますが、他のプロパティはインスタンス固有のものにしたいと考えています。これまで私が持っていたものは次のとおりです。少しボルグのようなクラスを作成する

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) 

答えて

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 

私はあなたがあなた自身の目的のために、この例を使用する方法を知っている願っています。私はあなたがコードで何を望んでいるのか本当にわからなかったので、私は推測を控え、最小限の例を書いた。

+0

これはうまくいった。私は2.4.3の\ @ shared.setter構文を変更しなければならず、\ @staticmethodを使用する必要がありました。そうしないと、バインドされていないメソッドのTypeErrorが返されます。 – shadowland

関連する問題