object knows which object called it?

Duncan Booth duncan.booth at invalid.invalid
Mon Apr 6 19:09:55 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 can do something like this if you really want (Zope does), but it is 
complex and confusing (Zope 3 has dropped implicit acquisition as being a 
bad idea). Have a look at 
http://www.zope.org/Documentation/Books/ZDG/current/Acquisition.stx
which has the following example:

import ExtensionClass, Acquisition

class C(ExtensionClass.Base):
  color='red'

class A(Acquisition.Implicit):

  def report(self):
    print self.color

a=A()
c=C()
c.a=A()

c.a.report() # prints 'red'

d=C()
d.color='green'
d.a=a

d.a.report() # prints 'green'

a.report() # raises an attribute error

and what you actually asked for: in the example above 'c.a.aq_parent is c'

If you want to confuse yourself you can install Zope's ExtensionClass and 
Acquisition modules from PyPi: 
http://pypi.python.org/pypi/Acquisition/2.12.0a1





More information about the Python-list mailing list