Search code examples
pythonobjectancestor

How to access the ancestor of an object in python


Suppose class A is inherited from B and B is inherited from C.

class C():
    def my_method(self):
        pass

class B(C):
    def my_method(self):
        pass

class A(B):
    def my_method(self):
        # Call my_method from B
        super(A, self).my_method()
        # How can I call my_method from C here ?

Question: How can I call my_method from C ?


Solution

  • You can call C's my_method() method simply by calling the "unbound" method directly, with self passed as an argument. For example:

    class C(object):
        def my_method(self):
            print('C.my_method')
    
    class B(C):
        def my_method(self):
            print('B.my_method')
    
    class A(B):
        def my_method(self):
            print('A.my_method')
            super(A, self).my_method()  # calls B.my_method(self)
            C.my_method(self)           # calls C.my_method(self)
    
    a = A()
    a.my_method()
    

    When run, that will print the following (note the (object) is required for super() to work on Python 2.x):

    A.my_method
    B.my_method
    C.my_method
    

    However, as others have pointed out, this may not be the best way to achieve what you want. Can you give a concrete example of what you're trying to achieve in context?