Can a python class have multiple grandparents?

Viewed 48

So I just come across a function called super() that will call every parent's version of the function, but when I tried several different things there are things that i didn't quite understand. Here, suppose I have 2 classes Human and Ghost

class Human:
    def __init__(self, name):
        print(name, "is a human")

class Ghost:
    def __init__(self, name):
        print(name, "is a ghost")

and I have 3 sub classes with Human and Ghost as their parent

# Child of Human class
class Run(Human):
    def __init__(self, name):
        print(name, "can run")
        super().__init__(name)

# Child of Human class
class Whisper(Human):
    def __init__(self, name):
        print(name, "can whisper")
        super().__init__(name)

# Child of Ghost class
class Fly(Ghost):
    def __init__(self, name):
        print(name, "can fly")
        super().__init__(name)

My problem are

  1. If I create a Robot class that has Run and Whisper classes as its parent
class Robot(Run, Whisper):
    def __init__(self):
        print("I am Robot")
        super().__init__('Robot')

and when i create r as Robot class, and run the code the result would be like this

>>> r = Robot()
I am Robot
Robot can run
Robot can whisper
Robot is a human
  1. And my second problem was, if I create a Robot class with Run and Fly as its parent
class Robot(Run, Fly):
    def __init__(self):
        print("I am Robot")
        super().__init__('Robot')

and create r as Robot class, run the code i get this result

>>> r = Robot()
I am Robot
Robot can run
Robot is a human

My Question is

  1. Why in the first number, in the Human class, print(name, "is a human") only run once not twice ? While both of the class Run and Whisper has super() function inside of them
  2. Why in the second number, the Run and Human classes was successfully called while the Fly and Ghost classes is not being called ?
  3. Is there a way to use multiple different grandparents in a single class ?
1 Answers

There is a good article about method resolution order:

In languages that use multiple inheritance, the order in which base classes are searched when looking for a method is often called the Method Resolution Order, or MRO. (In Python this also applies to other attributes.)

Classic classes used a simple MRO scheme: when looking up a method, base classes were searched using a simple depth-first left-to-right scheme. The first matching object found during this search would be returned. Read more here

Related