how to know who calls a method
Heather Coppersmith
me at privacy.net
Sat Apr 10 18:35:16 EDT 2004
On Fri, 09 Apr 2004 23:54:02 +0200,
Alex Garel <alex.garel at free.fr> wrote:
> It is because I would like an object to be aware of another
> object reading it so it can signal future change in its value to
> the last. I can use a getter which precise who is the reader but
> my attempt was to be able to use a normal getter (x=y) in a
> Phytonic fashion !
The usual solution involves some sort of "registration" (untested
and definitely needs more details and error checking, etc.):
class emitter:
def __init__( self ):
self.collectors = [ ]
self.data = None
def register_for_updates( self, collector ):
self.collectors.append( collector )
def set_data( self, newdata ):
self.data = newdata
for collector in self.collectors:
collector( self, newdata )
class collector:
def __init__( self, watch_this_object ):
watch_this_object.register_for_updates( self.collect_updates )
def collect_updates( self, other_object, new_data ):
print other_object, "just got new data:", new_data
Without this sort of set up, emitter.set_data wouldn't know
exactly what to do when there's new data anyway. This approach is
more flexible than a fixed method invocation should you have a
many-to-many emitter-to-collector relationship.
There's also no reason you couldn't wrap emitter.set_data up in
some sort of property so it would work as part of the getter
and/or setter for some attribute (but I don't like properties:
explicit is better than implicit).
HTH,
Heather
--
Heather Coppersmith
That's not right; that's not even wrong. -- Wolfgang Pauli
More information about the Python-list
mailing list