Python allows a class to inherit from multiple classes. Here is an example:
In this example, class D inherit from class B and C, class B and class C inherit from A.
In order to use python class mulitiple inheritance, one important question is how to call parent methods in child class. We will use some examples to show you this topic.
How does python child class call parent methods in python mulitiple inheritance?
Look at this example code:
class A(): def __init__(self): self.name = 'Class A' print("Run "+ self.name) class B(A): def __init__(self): self.name = 'Class B' print("Run "+ self.name) class C(A): def __init__(self): self.name = 'Class C' print("Run "+ self.name) class D(B, C): def __init__(self): self.name = 'Class D' print("Run "+ self.name) d = D()
Run this code, we will find this result:
Run Class D
From this result we can find: class D does not call parent B and C initialized methods defaultly, which means we should call parent initialized methods manually.
In python, we can use super().method_name() to call parent methods in child class. Here is an example:
class A(): def __init__(self): self.name = 'Class A' print("Run "+ self.name) class B(A): def __init__(self): super().__init__() self.name = 'Class B' print("Run "+ self.name) b = B()
In this example, we use super().__init__() to call parent class A in child class B. Run this code, you will see this output:
Run Class A Run Class B
However, this method only applies to python single inheritance. If one class inherit from multiple classes, how to call parent class methods using super()?
Look at this example:
class B(A): def __init__(self): self.name = 'Class B' print("Run "+ self.name) class C(A): def __init__(self): self.name = 'Class C' print("Run "+ self.name) class D(B, C): def __init__(self): super().__init__() super().__init__() self.name = 'Class D' print("Run "+ self.name) d = D()
Run this code, you will get this output:
Run Class B Run Class B Run Class D
We can find: parent C initialized method is not run.
How to call parent C initialized method?
We can use parent_class_name.parent_fun_name() to implement it. Here is an example:
class D(B, C): def __init__(self): B.__init__(self) C.__init__(self) self.name = 'Class D' print("Run "+ self.name) d = D()
Run this code, you will see:
Run Class B Run Class C Run Class D
If we have changed the order of parent functions, how about the output?
Look at this code:
class D(B, C): def __init__(self): C.__init__(self) B.__init__(self) self.name = 'Class D' print("Run "+ self.name) d = D()
Run this code, the output is:
Run Class C Run Class B Run Class D