pass
class LopCha2:
pass
class LopCon(LopCha1, LopCha2):
pass
Subclasses are defined from multiple parent classes and inherit the characteristics of both classes.
Parent classes can have the same properties or methods. The subclass will prioritize inheriting the attribute, the class method is first in the inheritance list.
In addition to being able to inherit from parent classes, you can also create new subclasses that inherit previous subclasses. This is called multi-level inheritance (Multilevel Inheritance).
In this case, the properties of the parent class and the previous subclass will be inherited by the new subclass.
Syntax:
class LopCha:
pass
class LopCon1(LopCha):
pass
class LopCon2(LopCon1):
pass
LopCon1 inherits LopCha, LopCon2 inherits LopCon1.
Class is derived from object. In a multiple inheritance scenario, any attributes that need to be retrieved will first be searched in the current class. If not found, search continues to the first parent class and left to right.
So the order of access will be [LopCon, LopCha1, LopCha2, object].
This order is also called linearization of LopCon and the set of rules used to find this order is called the Method Access Order (MRO).
In simple terms, MRO is used to display lists / tuples of parent classes of a particular class.
MRO is used in two ways:
>>> LopCon.__mro__
( ,
( ,
,
,
)
>>> LopCon.mro()
[ ,
[ ,
,
,
]
Here is a complex inheritance example and its visual display along with the MRO.
class X: pass
class Y: pass
class Z: pass
class A(X,Y): pass
class B(Y,Z): pass
class M(B,A,Z): pass
# Output:
# [ , ,
# [ , ,
# [ , ,
# , ,
# , ,
# , ,
# , ,
# , ,
# , ,
# ]
# ]
See more:
Last lesson: Inheritance (Inheritance) in Python
Next lesson: Overload operator in Python