object knows which object called it?

Anthra Norell anthra.norell at bluewin.ch
Mon Apr 6 13:44:44 EDT 2009


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), 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.
>
> Thanks in advance.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>   

B has to get into A somehow. Providing an installation method is no 
inconvenience if one remembers later not to bypass it.


class A:
    something_for_contained_to_show = 99
    def install_contained (self, B):
        B.container = self   # Provides B with a reference to A
        self.contained = B

class B:
    def method_with_container_access (self):
       print self.container   # Show container object
       print self.container.something_for_contained_to_show


 >>> a = A (); b = B (); a.install_contained (b)
 >>> b.method_with_container_access ()

<__main__.A instance at 0x019D5788>
99


Does this look like a good idea?


Frederic





More information about the Python-list mailing list