Inheritance is designed for code reuse and design reuse
In an inheritance relationship, an existing, well-designed class is called a parent class or base class, and a newly designed class is a subclass or a derived class
Derived classes can inherit the public members of the parent class, but cannot inherit their private members
If you need to call a method of a base class in a derived class, you can use the built-in function super () or the base class name. Method name () to implement
---------------------------------------------------------------------------
Python supports multiple inheritance, if the parent class has the same method name, and the parent class name is not specified when used in the child class.
The Python interpreter will search sequentially from left to right
#defining a base classclassPerson (object):#must use object as base class def __init__(self,name="', age=20,sex='Mans'): Self.setname (name) self.setage (age) self.setsex (sex)defSetName (self,name):if notisinstance (NAME,STR):Print('name must is string.') returnSelf .__name=namedefsetage (self,age):if notisinstance (age,int):Print('Age must is integer.') returnSelf .__age= AgedefSetsex (self,sex):ifSex! ='Mans' andSex! ='woman': Print('sex must is "man" or "woman".') returnSelf .__sex=SexdefShow (self):Print('Name:', self.__name) Print('Age :', self.__age) Print('Sex:', self.__sex)#define a derived class and call the base class methodclassTeacher (person):def __init__(self,name="', age=30,sex='Mans', id=215): Super (teacher,self).__init__(name,age,sex) Self.setid (ID)defsetId (self,id):if notisinstance (id,int):Print('ID must bu integer.') returnSelf .__id=IDdefShow (self): Super (Teacher,self). Show ()#methods that call the base class Print() if __name__=='__main__': Zhangle= Person ('Zhang Le', 19,'Mans') zhangle.show () Limu= Teacher ('Li Mu', 32,'Mans', 233) Limu.show () Limu.setid (666) Limu.show ()
Out
Name:zhang Leage:19sex:manname:li Muage:32sex:manname:li Muage:32sex:man
Python programming-object-oriented programming: inheritance