cool77
cool77

Reputation: 1136

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

Upvotes: 0

Views: 146

Answers (3)

cs95
cs95

Reputation: 402263

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'

Upvotes: 1

Sanket
Sanket

Reputation: 745

You have to modify the order of deriving the classes as class Multi(OtherBase, Base)

Upvotes: 1

Bart Van Loon
Bart Van Loon

Reputation: 1510

you can call it explicitly as OtherBase.display(self)

Upvotes: 1

Related Questions