object knows which object called it?

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Mon Apr 6 22:19:42 EDT 2009


On Mon, 06 Apr 2009 07:53:55 -0700, Reckoner 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),

You contradict yourself. 

If the methods inside B *need* A, then B is NOT a standalone object, it 
has a dependency, namely A.



> 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?

Not in any nice way. There's probably some sort of deep evil black magic 
that would work, for some definition of "work" that includes the phrase 
"fragile, incomprehensible and risky".

The solution is to admit your dependency instead of living in denial, and 
tell B who owns it:

B.owner = A

Now B.foo_func() can refer to B.owner and all is good.


For advanced work, you can make B.owner a weakref to A, and avoid 
creating a reference cycle which can sometimes be tricky to deal with.



-- 
Steven



More information about the Python-list mailing list