how to know who calls a method

A

Alex Garel

Hello,
Maybe it's a strange question.
I heard that salltalk use messages that are sent from one object to another.
It seems in other OO languages, method call is quite an implementation
of that. The only thing is, the receiver (instance which method is being
called) can't retrieve reference of the sender. Is it possible in Python
? Is there a standard way or a workaround.
I think about using frame stack (in module inspect) but it only gives me
the name of the function from which I was called, not a reference to the
object.
Why am I asking for such a feature ?
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 !
 
H

Heather Coppersmith

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top