Get caller class instance (object) inside method that was called?

2.4k views Asked by At

Let say I have

class A(object):
  def m1(self):
    B().m2()

class B(object):
  def m2(self):
    #return object of caller instance
    #let say 'a' is instance object this method was called from
    return a   

a = A().m1()
1

There are 1 answers

3
Anand S Kumar On

You can pass the caller instance, and make it a parameter of the called function itself. Something like -

class A(object):
  def m1(self):
    B().m2(self)

class B(object):
  def m2(self, obj):
    #return object of caller instance
    #let say 'a' is instance object this method was called from
    return obj   

a = A().m1()