Search code examples
pythonpython-2.7classderived-classbase-class

Accessing function from specific base class in python


i have two functions with same name in two different classes. and both those classes are inherited into a third class. so in my third class i want to access the function of specific class. how do i do it..

class Base(object):
    def display(self):
        return "displaying from Base class"

class OtherBase(object):
    def display(self):
        return "displaying from Other Base class"

class Multi(Base, OtherBase):
    def exhibit(self):
       return self.display() # i want the display function of OtherBase

Solution

  • There are two ways:

    1. Change the ordering of inheritance when defining Multi:

      Multi(OtherBase, Base)
      
    2. Explicitly call the display method of that class:

      xxxxx.display(self)
      

    For your particular use case, I would recommend the second. You can take advantage of default arguments and change your function's behaviour depending on how it is called.

    class Multi(Base, OtherBase):
         def exhibit(self, other_base=False):
             if other_base:
                 return OtherBase.display(self)
    
             return Base.display(self)
    

    minx = Multi()
    
    print minx.exhibit()
    'displaying from Base class'
    
    print minx.exhibit(other_base=True)
    'displaying from Other Base class'