object knows which object called it?

R. David Murray rdmurray at bitdance.com
Mon Apr 6 18:53:40 CEST 2009


Reckoner <reckoner at gmail.com> wrote:
> hi,
> 
> I have the following problem: I have two objects, say, A and B, which
> are both legitimate stand-alone objects with lives of their own.
> 
> A contains B as a property, so I often do
> 
> A.B.foo()
> 
> the problem is that some functions inside of B actually need A
> (remember I said they were both standalone objects), so I have to
> often do:
> 
> A.B.foo_func(A)
> 
> Which is kind of awkward.
> 
> Is there some way that B.foo_func() could somehow know that it was
> called as a property of A in this way?
> 
> Note that I'm looking for the calling object and NOT the calling
> function.

You could probably do this by creating a custom __getattr__ method (or
maybe even just a property) on A that would recognize B as an object and
return it wrapped in a class that would pick up the __getattr__ call on B
and translate it into a real call on B passing A as the first argument.

But that kind of magic is not considered good Python practice ("explicit
is better than implicit").  And it would be quite inefficient :)

I think the OO way to do this is to provide a method on A that does the
right thing:

    def Bfoo_func(self):
        self.B.foo_func(self)

Or maybe you could look at generic methods, which provide a way
to do multiple dispatch.

--
R. David Murray             http://www.bitdance.com




More information about the Python-list mailing list