I. Initial knowledge of inheritance
All classes in Python3 inherit from Object
classPARENTCLASS1:PassclassPARENTCLASS2:PassclassChildClass (PARENTCLASS1):Pass #Single InheritanceclassChildClass1 (PARENTCLASS1,PARENTCLASS2):Pass #Multiple InheritancePrint(ParentClass1.__base__)Print(ChildClass.__base__)#a parent class of the class is displayedPrint(ChildClass1.__base__)Print(ChildClass.__bases__)Print(ChildClass1.__bases__)#all the parent classes of the class are displayed
Two. Man and dog Wars
classAnimal:def __init__(SELF,NAME,AGGR,HP): Self.name=name Self.aggr=Aggr self.hp=HPdefEat (self):Print('In Animal')classPerson (Animal):def __init__(SELF,NAME,SEX,AGGR,HP): Self.sex=Sex#animal.__init__ (SELF,NAME,AGGR,HP)Super ().__init__(NAME,AGGR,HP)defAttack (Self,dog):Print('%s hit%s'%(self.name,dog.name)) dog.hp-=Self.aggrPrint(DOG.HP)defEat (self):Print(' in person') #animal.eat (self) #super (). Eat ()classDog (Animal):def __init__(SELF,NAME,KIND,AGGR,HP): Self.sex=Kind#animal.__init__ (self, name, AGGR, HP)Super ().__init__(NAME,AGGR,HP)defbite (self, person):Print('%s bit%s'%(Self.name, person.name)) person.hp-=Self.aggrPrint(PERSON.HP) Alex= Person ('Alex','Felame', 1,250) Hei= Dog ('Little Black','Teddy', 260,10000) Alex.attack (HEI) hei.bite (Alex)#alex.eat ()Person.eat (Alex) animal.eat (Alex) Super (Person,alex) eat ()
Three. Single Inheritance
Do not occur with cyclic inheritance
Dependency Inversion principle:
High-rise modules should not rely on low-level modules
classA:defWahaha (self):Print('In A')classB (A):defWahaha (self):Print('In B')classC (B):defWahaha (self):Print('In C')classD (C):defWahaha (self):Print('In D') d=D () D.wahaha ()
Three. Multi-inheritance and diamond inheritance
All classes in Python3 inherit the object by default
If a class inherits object, this class is called the new class.
Not inheriting the object class is called the Classic class
Depth-first-breadth-first is a traversal algorithm that walks through all the items in the diagram and does not repeat
The classic class follows the depth-first algorithm and there is no MRO method Python2
The new class follows the breadth first algorithm has the MRO method Py2 Py3
PY3 Super
The super in single inheritance is looking for the parent class
Multi-inheritance Super search trajectory is based on MRO (breadth first) Order
classA:defWangwang (self):Print('In A')classB (A):defWangwang (self): Super (). Wangwang ()#' in C ' Print('In B')classC (A):defWangwang (self):Print('In C')classD (B,C):PassD=D () D.wangwang ()
Python object-oriented (inheritance of classes)