5
class Parent1(object):
    def foo(self):
        print "P1 foo"

    def bar(self):
        print "P1 bar"


class Parent2(object):
    def foo(self):
        print "P2 foo"

    def bar(self):
        print "P2 bar"



class Child(Parent1, Parent2):
    def foo(self):
        super(Parent1, self).foo()

    def bar(self):
        super(Parent2, self).bar()

c = Child() 
c.foo()
c.bar()

The intention is to inherit foo() from Parent1 and bar() from Parent2. But c.foo() resulting for parent2 and c.bar() is reulting error. Please point to the problem and provide solution.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
SamCodes
  • 384
  • 4
  • 17
  • 2
    The first argument to `super` is the class to start looking "above" in the inheritance hierarchy, so `foo` will be from `Parent2` and `bar` will be from `object` (which has no such attribute, presumably causing the error you mention only in passing). Instead, use `Child` and `Parent1` in your `super` calls. – jonrsharpe May 09 '16 at 07:54
  • Why not just use `Parent1.foo()` and `Parent2.bar()`? – acdr May 09 '16 at 08:08
  • @jonrsharpe : Thanks for clarification. the possible duplicate question you suggested has initialization function __init__ . so, I was not sure that normal methods and __init__ will follow the same rule for inheritance – SamCodes May 09 '16 at 08:31
  • 1
    All instance methods, `__init__` and other *"magic"* methods included, follow the same rules. – jonrsharpe May 09 '16 at 08:55

1 Answers1

4

You could call the methods directly on the parent classes, providing the self argument manually. This should give you the highest level of control and be the easiest way to understand. From other points of view it might be suboptimal though.

Here's only the Child class, the rest of your code stays the same:

class Child(Parent1, Parent2):
    def foo(self):
        Parent1.foo(self)

    def bar(self):
        Parent2.bar(self)

Running your snippet with the described changes results in the desired output:

P1 foo
P2 bar

See this code running on ideone.com

Byte Commander
  • 6,506
  • 6
  • 44
  • 71
  • We provide self to when we define a method to refer the object. But when we are calling the method from child class we are providing it manually. So How does it work? – SamCodes May 09 '16 at 08:44
  • Inside the class `MyClass`, you may have a method defined like this `def foo(self, arg1, arg2)`. When you run `my_instance = MyClass()`, you create a new instance of your class. Now you can call the method from the instance object like this: `my_instance.foo("This is arg1", "This is arg2")`. This way, the `self` parameter gets implicitly set to the instance object on which we call the method, i.e. here it would be `my_instance`. Now if we call the same method on a specific class, we have to provide the `self` argument explicitly: `MyClass.foo(my_instance, "This is arg1", "This is arg2")`. Ok? – Byte Commander May 09 '16 at 09:27