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
- If I create a
Robotclass that hasRunandWhisperclasses 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
- And my second problem was, if I create a
Robotclass withRunandFlyas 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
- Why in the first number, in the
Humanclass,print(name, "is a human")only run once not twice ? While both of the classRunandWhisperhassuper()function inside of them - Why in the second number, the
RunandHumanclasses was successfully called while theFlyandGhostclasses is not being called ? - Is there a way to use multiple different grandparents in a single class ?