InfoLearner
InfoLearner

Reputation: 15598

Python multi-inheritance. Is this a bug?

In the example below, I expected to see:

CarChild1
CarChild2

But it prints:

CarChild1
CarChild1

The scenario is that I have a class that inherits 2 classes. It needs to call the run() function of both of the parent classes in the right sequence, but for some reason, it only calls the first parent class's function.

The sample code below illustrates the issue:

class CarChild1:
    def run(self):
        self._print_name()

    def _print_name(self):
        print('CarChild1')

class CarChild2:
    def run(self):
        self._print_name()

    def _print_name(self):
        print('CarChild2')

class CarChild3(CarChild1, CarChild2):
    def run(self):
        CarChild1.run(self)
        CarChild2.run(self)

carChild3 = CarChild3()
carChild3.run()

Upvotes: 1

Views: 62

Answers (1)

khelwood
khelwood

Reputation: 59146

Your call to self._print_name() will call the _print_name method of the object based on its class hierarchy, not necessarily the one defined in the same class you are calling it from.

If you specifically want CarChild2 to use the _print_name method declared in CarChild2, you could call CarChild2._print_name(self). Or you could just give your different _print_name methods different names, since you want them to work independently.

Or if you call your print method __print_name (with a double underscore prefix) instead of _print_name then Python will internally alter their names so that the right one is called in each class and cannot* be called outside of it. (The methods are then essentially private to the class.)

* They can, but only by working around the name-mangling mechanism

Upvotes: 2

Related Questions