Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In general we don't want that <code>func</code> to have access back to the calling instance of <code>A</code> because this breaks <a href="http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29" rel="noreferrer">encapsulation</a>. Inside of <code>b.func</code> you should have access to any args and kwargs passed, the state/attributes of the instance <code>b</code> (via <code>self</code> here), and any globals hanging around. </p> <p>If you want to know about a calling object, the valid ways are: </p> <ol> <li>Pass the calling object in as an argument to the function </li> <li>Explicitly add a handle to the caller onto <code>b</code> instance sometime before using <code>func</code>, and then access that handle through <code>self</code>. </li> </ol> <p><em>However</em>, with that disclaimer out of the way, it's still worth knowing that python's introspection capabilities are powerful enough to access the caller module in some cases. In the CPython implementation, here is how you could access the calling <code>A</code> instance without changing your interfaces:</p> <pre><code>class A(): def go(self): b=B() b.func() class B(): def func(self): import inspect print inspect.currentframe().f_back.f_locals['self'] if __name__ == '__main__': a = A() a.go() </code></pre> <p>Output:</p> <pre><code>&lt;__main__.A instance at 0x15bd9e0&gt; </code></pre> <p>This might be a useful trick to know about for debugging code sometimes. But it would not be a sensible design decision to ever access the stack frames like this in the case that <code>B.func</code> actually needed to use <code>A</code> for any reason. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload