Follow the Wowapps design pattern to read the copy.
Http://dongweiming.github.io/python-observer.html
#This is the Observer base class .classSubject (object):def __init__(self): Self._observers= [] #to add dependent objects defAttach (self, observer):if notObserverinchSelf._observers:self._observers.append (Observer)#Cancel Add defDetach (self, observer):Try: SELF._OBSERVERS.REMOVE (Observer)exceptValueError:Pass #This is just a notification of new changes to the dependent objects registered above defNotify (Self, modifier=None): forObserverinchself._observers:#filter conditions can be set for updates that do not meet the filter criteria ifModifier! =observer:observer.update (self)#Viewer ClassclassData (Subject):def __init__(Self, name="'): Super (Data, self).__init__() Self.name=name Self._data=0#python2.6 adds a new notation, gets the property, sets the property to (assuming the property name is X) @x.setter, and deletes it as @x.deleter@propertydefdata (self):returnself._data @data. Setterdefdata (self, value): Self._data=value self.notify ()#There are 2 observers, that is, dependent objects, each time data changes, these 2 view will changeclassHexviewer (object):defUpdate (self, subject):Print 'hexviewer:subject%s has data 0x%x'%(Subject.name, Subject.data)classDecimalviewer (object):defUpdate (self, subject):Print 'decimalviewer:subject%s has data%d'%(Subject.name, Subject.data)if __name__=='__main__': Data1= Data ('Data 1') Data2= Data ('Data 2') View1=decimalviewer () view2=hexviewer () Data1.attach (view1) Data1.attach (view2) Data2.attach (view2) Data2.attach (view1)Print "Setting Data 1 = ten"Data1.data= 10Print "Setting Data 2 ="Data2.data= 15Print "Setting Data 1 = 3"Data1.data= 3Print "Setting Data 2 = 5"Data2.data= 5Print "Update data1 ' s view2 Because view1 is being be filtered"data1.notify (modifier=view1)Print "Detach hexviewer from Data1 and data2."Data1.detach (VIEW2) Data2.detach (VIEW2)Print "Setting Data 1 = ten"Data1.data= 10Print "Setting Data 2 ="Data2.data= 15
Learn the basics of Python-data structures, algorithms, design patterns---observer patterns