0

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
3
  • class Multi(OtherBase, Base) reverse the order of inheritance. Commented Sep 8, 2017 at 9:16
  • that works by changing the order. but what if i am accessing from outside the class. something like below minx = Multi() print minx.exhibit() Commented Sep 8, 2017 at 9:27
  • Added an answer. Commented Sep 8, 2017 at 9:34

3 Answers 3

1

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'
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.