继承是为代码复用和设计复用而设计的
在继承关系中,已有的、设计好的类称为父类或基类,新设计的类为子类或派生类
派生类可以继承父类的公有成员,但不能继承其私有成员
如果需要在派生类中调用基类的方法,可以使用内置函数super()或者通过 基类名.方法名() 实现
---------------------------------------------------------------------------
python支持多继承,如果父类中有相同的方法名,而在子类中使用时没有指定父类名,
则python解释器将从左到右按顺序搜索
# 定义基类class Person(object): # 必须以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)# 定义派生类,并调用基类方法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() # 调用基类的方法 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 leage: 19sex: manname: li muage: 32sex: manname: li muage: 32sex: man