If I have a class that contains a method, and I call that method from an instance, how do I get the specific instance it was called from?
e.g. I have a class:
class foo: def __init__(self): pass def do_something(self): bar()
I also have a function:
def bar(): print()
If i make an object, e.g. obj = foo()
, and then i call obj.do_something()
, How would i get obj
from inside my bar()
function?
Advertisement
Answer
Using the inspect module, you can get the caller frame and access its local variables, in particular the self
argument representing the instance:
import inspect def bar(): caller = inspect.stack()[1].frame localvars = caller.f_locals self = localvars['self']