继承
学习如何从其他类继承属性。
继承 是 CoddyKit 上的免费 Python For Kids 课时。 这是第 3 节课,共 5 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Python For Kids 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Python For Kids 课程共包含 5 节课。
继承
欢迎回到面向对象编程(OOP)课程!今天,我们将学习 Python 中的继承。继承是一项强大的功能,允许类从其他类继承属性和行为。

什么是继承?
继承是面向对象编程中的一个基本概念,它使新类(子类)能够获得现有类(父类)的 attributes 和方法。继承促进了代码复用,并在类之间建立了自然的层次关系。
- 父类:被继承的类。
- 子类:从父类继承的类。
让我们探索继承在 Python 中的工作方式!
继承的优点
继承具有以下几项优点:
- 代码复用:无需重写即可复用现有代码。
- 可维护性:更易于更新和管理代码。
- 层次结构:在类之间建立逻辑关系。
现在,让我们看看如何在 Python 中实现继承。
定义父类
首先,我们将定义一个父类,其中包含可供子类继承的公共 attributes 和方法。
示例:
# Defines the Animal parent class
class Animal:
def __init__(self, name):
self.name = name # Sets the name of the animal
def speak(self):
print(self.name + " makes a sound.") # Generic speak method
创建子类
接下来,我们将创建一个从父类继承的子类。子类可以拥有额外的 attributes 和方法,也可以重写现有方法。
示例:
# Defines the Dog child class inheriting from Animal
class Dog(Animal):
def speak(self):
print(self.name + " says Woof!") # Overrides the speak method
使用子类
现在,让我们创建一个子类的对象,看看它如何从父类继承属性和方法。
示例:
# Creates an object of the Dog class
my_dog = Dog("Buddy")
# Calls the speak method
my_dog.speak() # Output: Buddy says Woof!
多重继承
Python 允许一个类从多个父类继承,并组合这些父类的 attributes 和方法。这称为多重继承。
- 父类:所有被继承属性和方法的类。
示例:
# Defines the Flyer parent class
class Flyer:
def fly(self):
print("I can fly!")
# Defines the Swimmer parent class
class Swimmer:
def swim(self):
print("I can swim!")
# Defines the Duck child class inheriting from both Flyer and Swimmer
class Duck(Flyer, Swimmer):
def speak(self):
print("Quack!")
使用多重继承
让我们创建一个 Duck 类的对象,看看它如何从两个父类继承方法。
示例:
# Creates an object of the Duck class
donald = Duck()
# Calls methods inherited from both parent classes
donald.fly() # Output: I can fly!
donald.swim() # Output: I can swim!
# Calls the speak method defined in the Duck class
donald.speak() # Output: Quack!
# Defines the Vehicle parent class
class Vehicle:
def __init__(self, brand):
self.brand = brand # Sets the brand of the vehicle
def drive(self):
print(self.brand + " is driving.")
# Defines the Car child class inheriting from Vehicle
class Car(Vehicle):
def drive(self):
print(self.brand + " is driving a car.")
# Creates an object of the Car class
my_car = Car("Toyota")
# Calls the drive method
my_car.drive()
做得很好!
您已经学会了如何在 Python 中使用继承,创建从父类继承属性和方法的子类。继承有助于您构建结构清晰且可复用的代码,使程序更加高效并且更易于管理。请继续练习,创建自己的类并探索不同的继承场景!

常见问题解答
「继承」课时是免费的吗?
是的 — 「继承」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Python For Kids 课程的其余内容,请升级到 CoddyKit PRO。 Python For Kids 课程共包含 5 节课。
「继承」这节课中我会学到什么?
学习如何从其他类继承属性。 你通过在浏览器中直接运行的动手代码来练习 Python For Kids,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Python For Kids 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Python For Kids 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 5 节。
「继承」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Python For Kids 课中编写并运行代码吗?
能。每节 Python For Kids 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。