继承:
是从已有类中派生出新类,新类具有原类的数据属性和行为,并能扩展出新的能力,
派生就是从一个已有的类衍生出新类,在新的类上添加新的属性和行为
作用:
1、用继承派生机制可以将一些共有功能加在基类中,实现代码的共享
2、在不改变超类的基础上,改变原有的功能
单继承:
语法:
class 类名(超类名):
语句块
示例:
class Human: # Human 派生 出了Student类
def say(self,what): #说话的行为
print('说:',what)
def walk(self,distance): #走路的行为
print('走了',distance,'公里')
class Student(Human): #继承Human 类
def study(self ,s):
print('学生在学习',s)
class Teacher(Human):
def teach(self , that):
print('老师正在教',that)
h1=Human()
h1.say('今天天气阳光明媚')
h1.walk(100)
print('-------------------------')
s1=Student()
s1.say('今天晚上吃什么')
s1.walk(3)
s1.study('python')
print('-------------------------')
t1=Teacher()
t1.say('今天下班早点回家')
t1.walk(3)
t1.teach('面向对象')
继承说明:
任何类都可以直接或间接的继承自object 类
object类是一切类的超类
类内的__base__属性:
此属性用来记录此类的基类
覆盖: override
什么是覆盖
覆盖是指在有继承派生关系的类中,子类中实现了与基类(超类)同名的方法,在子类实例调用方法时,实际调用的是子类中的覆盖版本,这种现象叫做覆盖
示例:
class A:
def work(self):
print('"a类的方法被调用')
#override
class B(A):
def work(self):
print('"b类的方法被调用')
b=B()
b.work()