0

I wonder if there is a way in Python to access the class which the object which the method belongs to is being called from. For example:

class A:
    def __init__(self):
        self.b = B()
    def foo(self):
        print('A')

class B:
    def bar(self):
        <something here>.foo()


a = A()
a.b.bar()

Basically I would like B's method bar to invoke A's method foo. And if b was an attribute of some other class C, to invoke C's version of foo instead.

jsstuball
  • 4,104
  • 7
  • 33
  • 63
  • 2
    Possible duplicate of [Get class that defined method](https://stackoverflow.com/questions/961048/get-class-that-defined-method) – ndmeiri Feb 19 '18 at 06:10
  • Nope, please re-read my question. – jsstuball Feb 19 '18 at 06:15
  • 1
    The keywords are misleading. Your example (so far) has nothing to do with 'inheritance', but is a problem of referencing. Manually establishing a back-reference (to the INSTANCE of A that instanciated B) in B, as proposed by AKS, provides a way to call A-instance's foo method. But in python, a method does not necessarily 'belong' to a particular class. It resides in memory and is initially referenced by the class that defines it, but it can as well be referenced by one or more other classes. If you want to know, which method called the function, you have to inspect the traceback stack. – Michael S. Feb 19 '18 at 07:32

1 Answers1

1

You could add a reference to the class which instantiates B:

class A:
    def __init__(self):
        # pass self while instantiating B
        self.b = B(self)
    def foo(self):
        print('A')

class B:
    def __init__(self, rel_obj):
        self.rel_obj = rel_obj
    def bar(self):
        self.rel_obj.foo()   # access foo() using self.rel_obj

Similarly, you could pass an object of class C to invoke C's version of foo method.

AKS
  • 18,983
  • 3
  • 43
  • 54