- 1
- 0
- 约2.21千字
- 约 7页
- 2026-01-13 发布于陕西
- 举报
Python程序设计
PythonProgramming
广东机电职业技术学院人工智能学院
SchoolofArtificialIntelligence
GuangdongMechanicalElectronicalPolytechnic
Python面向对象
什么是继承?
5.3Python类的继承
继承是一种创建新类的机制,新类(子类/派生类)可以获得另一个类(父类/基类/超类)的属性和方法,并可以扩展或修改这些功能。
继承的意义?
代码复用:避免重复编写相同代码。
层次化抽象:建立从一般到特殊的类层次关系。
多态支持:不同子类可以对同一方法有不同的实现。
继承的基本语法
5.3Python类的继承
继承是一种创建新类的机制,新类(子类/派生类)可以获得另一个类(父类/基类/超类)的属性和方法,并可以扩展或修改这些功能。
classParentClass:
#父类定义
pass
classChildClass(ParentClass):
#子类定义
pass
class父类类名:
def父类构造函数
def方法
class派生类(父类类名):
def派生类构造函数:
父类类名.父类构造函数#重写
可增加属性
可重写父类的方法#如不重写,就会继承父类的方法
……
简单
具体
继承的基本语法
5.3Python类的继承
例1:
classAnimal:
def__init__(self,name):
self.name=name
defspeak(self):
return动物声音
classDog(Animal):
defspeak(self):
returnf{self.name}sayswoof!
dog=Dog(Buddy)
print(dog.speak())#输出:Buddysayswoof!
继承的基本语法
5.3Python类的继承
例2:
classPerson:
父类:人
def__init__(self,name,age):
Person类的构造函数
self.name=name
self.age=age
print(Person类的构造函数被调用)
defintroduce(self):
自我介绍方法
returnf我叫{self.name},今年{self.age}岁
classStudent(Person):
子类:学生,继承自Person
def__init__(self,name,age,student_id):
Student类的构造函数
#调用父类的构造函数初始化name和age
super().__init__(name,age)
self.student_id=student_id
print(Student类的构造函数被调用)
defstudy(self,subject):
学生学习的方法
returnf{self.name}正在学习{subject}
#重写父类的introduce方法
defintroduce(self):
扩展的自我介绍方法
parent_intro=super().introduce()#调用父类方法
returnf{parent_intro},我的学号是{self.student_id}
student=Student(张三,20,
输出:
Person类的构造函数被调用
Student类的构造函数被调用
print(student.introduce())
#输出:我叫张三,今年20岁,我的学号print(student.study(Python编程))
#输出:张三正在学习Python编程
父类
子类
使用
注意:当子类定义了__init__方法时,必须显式调用父类构造函数
实验报告
5.3Python类的继承
创建1个Person类,要求有namegenderage等属性;show方法:输出其namegender
您可能关注的文档
- Set接口及其实现类赵耀宏63课件讲解.pptx
- PracticalEnglishforInternationalCruiseShipCrew国际邮轮服务英语50课件讲解.pptx
- PracticalEnglishforInternationalCruiseShipCrew国际邮轮服务英语53课件讲解.pptx
- PracticalEnglishforInternationalCruiseShipCrew国际邮轮服务英语57课件讲解.pptx
- PracticalEnglishforInternationalCruiseShipCrew国际邮轮服务英语61课件讲解.pptx
- PracticalEnglishforInternationalCruiseShipCrew国际邮轮服务英语68课件讲解.pptx
- PracticalEnglishforInternationalCruiseShipCrew国际邮轮服务英语74课件讲解.pptx
- PracticalEnglishforInternationalCruiseShipCrew国际邮轮服务英语78课件讲解.pptx
- PracticalEnglishforInternationalCruiseShipCrew国际邮轮服务英语79课件讲解.pptx
- PracticalEnglishforInternationalCruiseShipCrew国际邮轮服务英语80课件讲解.pptx
- Python程序设计Python数据类型12课件讲解.pptx
- Python程序设计Python数据类型22课件讲解.pptx
- Python程序设计Python数据类型36课件讲解.pptx
- Python程序设计Python序列数据07课件讲解.pptx
- Python程序设计Python序列数据24课件讲解.pptx
- Python程序设计Python序列数据47课件讲解.pptx
- Python程序设计Python序列数据67课件讲解.pptx
- Python程序设计初识Python77课件讲解.pptx
- Python基础程序设计二大数据技术在财务中的应用79课件讲解.pptx
- Python爬虫BeautifulSoup04课件讲解.pptx
原创力文档

文档评论(0)