object knows which object called it?

Ricardo Aráoz ricaraoz at gmail.com
Wed Apr 8 02:28:28 CEST 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
>>
>>  
Maybe this would work for you?

>>> class B(object) :
...     def __init__(self, owner=None) :
...         self.owner = owner
...     def someMethod(self) :
...         print self.owner.name
...
>>> class A(object) :
...     def __init__(self, name='class A') :
...         self.B = B(owner=self)
...         self.name = name
...
>>> instA1 = A('one')
>>> instA2 = A('two')
>>> instA1.B.someMethod()
one
>>> instA2.B.someMethod()
two
>>>







More information about the Python-list mailing list