Inheritance is designed for code reuse and design reuse
In the inheritance relationship, the existing and designed classes are called parent classes or base classes, and the newly designed classes are called subclasses or derived classes
A derived class can inherit the public members of the parent class, but not its private members
If you need to call the method of the base class in the derived class, you can use the built-in function super() or use the base class name.method name() to achieve
---------------------------------------------------------------------------
Python supports multiple inheritance. If there is the same method name in the parent class, but the parent class name is not specified when used in the child class,
then the python interpreter will search sequentially from left to right
#Define base class
class Person(object): #Must be based on object
def __init__ (self,name= '' ,age=20,sex= ' man ' ):
self.setName(name)
self.setAge(age)
self.setSex(sex)
def setName(self,name):
if not isinstance(name,str):
print('name must be string.')
return
self.__name=name
def setAge(self,age):
if not isinstance(age,int):
print('age must be integer.')
return
self.__age=age
def setSex(self,sex):
if sex != 'man' and sex != 'woman':
print('sex must be "man" or "woman".')
return
self.__sex = sex
def show(self):
print('name:',self.__name)
print('age:',self.__age)
print('sex:',self.__sex)
#Define the derived class and call the base class method
class Teacher(Person):
def __init__ (self,name= '' ,age=30,sex= ' man ' ,id=215 ):
super(Teacher,self).__init__(name,age,sex)
self.setId(id)
def setId(self,id):
if not isinstance(id,int):
print('id must bu integer.')
return
self.__id = id
def show(self):
super(Teacher, self).show() #Call the method of the base class
print ()
if __name__=='__main__':
zhangle = Person( ' zhang le ' ,19, ' man ' )
zhangle.show()
limu = Teacher( ' li mu ' ,32, ' man ' ,233 )
limu.show()
limu.setId( 666 )
limu.show()
out:
name: zhang le
age: 19
sex: man
name: li mu
age: 32
sex: man
name: li mu
age: 32
sex: man