1

I have two class and methods having same name .I have the object of derived class. When i call the method (foo) from derived class object it should call the base class method.

class A:
    def foo(self):
        print "A Foo"

class B(A):
    def foo(self):
        print "B Foo"

b = B()
b.foo() # "B Foo"

After doing some search i got some solution as below and not sure whether it is proper way of doing it or not

a = A()
b.__class__.__bases__[0].foo(a) # A Foo

Is there any better way of doing it.

1
  • You should upgrade to Python 3. If you must use Python 2, A should inherit from object to make it a new-style class (where "new" means Python 2.2 and up, or about 17 years old!), then you can use super. Commented May 8, 2019 at 7:29

2 Answers 2

2

If you're using Python 3, use super:

class A:
    def talk(self):
        print('Hi from A-land!')

class B(A):
    def talk(self):
        print('Hello from B-land!')

    def pass_message(self):
        super().talk()

b = B()
b.talk()
b.pass_message()

Output:

Hello from B-land!
Hi from A-land!

You can do the same thing in Python 2 if you inherit from object and specify the parameters of super:

class B(A):
    def talk(self):
        print('Hello from B-land!')

    def pass_message(self):
        super(B, self).talk()

b = B()
b.talk()
b.pass_message()

Output:

Hello from B-land!
Hi from A-land!

You can also call the method as if it were a free function:

A.talk(b)
B.talk(b)  # the same as b.talk()

Output:

Hi from A-land!
Hello from B-land!
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for your answer. I have multiple methods in the derived class and base class with the same name. Based on scenario i need to call the methods of A or B.
@Gopi: That sounds like you picked a bad design and you should redesign it.
@user2357112 you are correct. Working with legacy. :(
@Gopi How does that relate to my answer?
@gmds What i meant here is that i have multiple methods overridden in the child class. I cannot create methods like pass_message for all to call the base class methods.
|
0

When you call the method (foo) from derived class object, it won't call the base class method, because you're overriding it. You can use another method name for your base class or derived class to solve the interference.

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.