[Tutor] class accessing another's updated property

Alan Gauld alan.gauld at btinternet.com
Thu Nov 15 23:10:19 CET 2007

"ted b" <phpmoonlighter at yahoo.com> wrote

>I want class One to be able to access access class
> Two's value property after its been updated. Everytime
> I try (by running, say testTwo().value) I get the
> __init__ value.

Others have explained that you need to use instances
or class attributes.

I'll tackle the woder issue of synchronising
classes/instances. If you have a class (or classes) that
depend on another it is common to set up a publish/subscribe
mechanism so that the owner of the data notifies the subscribed
classesof changes. This can be a simple boolean flag to indicate
that something has changed or it can contain a list of the
published attributes that have changed(usually as a list of
name/value pairs or a dictionary)

This allows the subscribed objects to fetch the updated value
(or update their copy) whenever the master object changes value.
This is particularly common in the Model View architectures
used in GUIs where the model data may change and all
dependant views in the GUI need to be updated in synch.

To implement this requires that you create a publish/subscribe
method pair in the master class and then call publish every time
any of the public data changes. Client classes need to subscribe
to the master when created - ie in the init method. One common
way to do this with an established data class is via inheritance
and overloaded opertators, like so:

class Master:
    def __init__(self, v1,v2,v3):
       self.v1 = v1
       self.v2 = v2
       self.v3 = v3
    def m1(self): self.v1 = 42
    def m1(self): self.v2 = 66
    def m1(self): self.v3 = 27

class PublishedMaster(Master):
    def __init__(self,v1,v2,v3):
        self.subs = []
    def subscribe(self.obj):
    def publish(self):
        for obj in self.subs:
            obj.update(self)    # notify subscriber of change
    def m2(self):
    def m3(self):

class client:
    def __init__(self, master):
        self.myVal = master.v2
        master.subscribe(self)   # register interest in updates
    def update(self.publisher):
        self.v2 = publisher.v2

This allows the subscriber classes to be informed of any changes
to either v2 or v3. The client class is only interested in v2 so 
its local copy when it receives the update message from the master.

Much more sophisticated regimes can be created but for simple
scenarios this suffices.Take care to avoid infinite loops caused by
calling a master method in client.update that results in the masdter
sending updates!


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list