Multiple inheritance of classes

1


class Person(object):
    def talk(self):
        print('talk')
    def run(self):
        print('person run')

class Car(object):
    def run(self):
        print('car run')

class PersonCarRobot(Person, Car):
    def fly(self):
        print('fly')

person_car_robot = PersonCarRobot()
person_car_robot.talk()
person_car_robot.run()
person_car_robot.fly()

Execution result of 1


talk
person run
fly

PersonCarRobot class It inherits both the Person class and the Car class. So It has methods for both classes.

here, Both the Person class and the Car class have a method called run.

in this case, It is a class PersonCarRobot (Person, Car) An image that inherits the Person class first and inherits what is not from the Car class. Therefore, the run method of Car class is not inherited.

If you replace it with class PersonCarRobot (Car, Person) Inherit the Car class first, and inherit what is not from the Person class. The run method of the Person class is not inherited.

2


class Person(object):
    def talk(self):
        print('talk')
    def run(self):
        print('person run')

class Car(object):
    def run(self):
        print('car run')

class PersonCarRobot(Car, Person):
    def fly(self):
        print('fly')

person_car_robot = PersonCarRobot()
person_car_robot.talk()
person_car_robot.run()
person_car_robot.fly()

Execution result of 2


talk
car run
fly

Recommended Posts

Multiple inheritance of classes
Multiple inheritance
Copy of multiple List
EP 26 Use Multiple Inheritance Only for Mix-in Utility Classes
Sum of multiple numpy arrays (sum)
Catch multiple types of exceptions
Optimal placement of multiple images
Install multiple versions of Python
[ev3dev × Python] Control of multiple motors
[Python of Hikari-] Chapter 09-03 Class (inheritance)
[Python] Extension using inheritance of matplotlib (NavigationToolbar2TK)
[Python] What is inherited by multiple inheritance?
Install multiple versions of Polyphony using venv
Comparison of class inheritance and constructor description
Get out of multiple loops at once
Summary of modules and classes in Python-TensorFlow2-
[Bash] Redirection of multiple lines to multiple files