2

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()
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Andrius
  • 19,658
  • 37
  • 143
  • 243
  • You should try to search first. Look [here](http://stackoverflow.com/questions/900392/getting-the-caller-function-name-inside-another-function-in-python) for example. Alternative would be to give calling object as argument to the method. – Kelo Jun 16 '15 at 11:09

1 Answers1

0

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()
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
  • Yeah, that would be nice. But what if I don't have luxury of passing that object? I mean I don't have a control when someone calls method `m2` from any other method, that they would pass object too. So I have to check myself inside `m2` to see which object it was passed from. – Andrius Jun 16 '15 at 12:59
  • Are you the one defining the object `m2` ? If so, if `m2` has the second parameter, then they would surely need to pass some value into it, without passing the object that you were hoping to get, the logic would not work correctly, right? So, I am guessing that would ensure that they do pass in the correct object? – Anand S Kumar Jun 16 '15 at 14:24
  • Well logic is that m1 (or any other method) that is calling m2 is not aware of any new argument. It just calls that `m2`. And I need to modify `m2` so it would find which object called it, so it could do something about that object. – Andrius Jun 17 '15 at 07:12