Python程序设计Python面向对象30课件讲解.pptxVIP

  • 1
  • 0
  • 约2.21千字
  • 约 7页
  • 2026-01-13 发布于陕西
  • 举报

Python程序设计Python面向对象30课件讲解.pptx

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

文档评论(0)

1亿VIP精品文档

相关文档