0Pricing
Python For Kids · 课时

多态

探索高级面向对象编程概念。

多态 是 CoddyKit 上的免费 Python For Kids 课时。 这是第 5 节课,共 5 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Python For Kids 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Python For Kids 课程共包含 5 节课。

多态

欢迎回到面向对象编程(OOP)课程!今天,我们将探索 Python 中的多态,这是一种功能强大的概念,允许对象呈现多种形式。

多态 — 插图 1

什么是多态?

多态是 OOP 中的一个基本概念,它允许将不同类的对象视为某个共同父类的对象。它使同一个方法能够根据调用它的对象而表现出不同的行为。

  • 定义:“多种形式”——不同对象能够以各自独特的方式响应同一个方法调用。
  • 用途:通过允许对象相互替换来增强代码的灵活性和可组合性。

让我们看看多态在 Python 中是如何工作的!

实现多态

在 Python 中,可以通过方法重写以及使用适用于不同对象类型的内置函数来实现多态。

  • 方法重写:在子类中重新定义父类中已经定义的方法。
  • 内置函数:例如适用于各种数据类型的 len() 函数。

让我们详细了解方法重写。

方法重写

方法重写允许子类为父类中已经定义的方法提供特定的实现。这是多态的一个关键方面。

示例:

# Defines the Animal parent class with a speak method
class Animal:
    def speak(self):
        print("The animal makes a sound.")  # Generic speak method

使用重写的方法创建子类

让我们创建继承自 Animal 的子类,并重写 speak 方法来提供特定的行为。

示例:

# Defines the Dog child class inheriting from Animal
class Dog(Animal):
    def speak(self):
        print("The dog barks.")  # Overridden speak method

# Defines the Cat child class inheriting from Animal
class Cat(Animal):
    def speak(self):
        print("The cat meows.")  # Overridden speak method

使用重写的方法实现多态

现在,让我们创建子类的对象,看看它们如何使用相同的方法名表现出不同的行为。

示例:

# Creates objects of Dog and Cat classes
dog = Dog()
cat = Cat()

# Calls the speak method on both objects
dog.speak()  # Output: The dog barks.
cat.speak()  # Output: The cat meows.

使用内置函数实现多态

多态并不局限于用户定义的类。Python 的内置函数(例如 len())可以处理不同的数据类型,展示了多态行为。

示例:

# Uses len() with a list
my_list = [1, 2, 3, 4]
print(len(my_list))  # Output: 4

# Uses len() with a string
my_string = "Hello"
print(len(my_string))  # Output: 5

# Uses len() with a dictionary
my_dict = {"a": 1, "b": 2}
print(len(my_dict))  # Output: 2

示例程序:计算形状面积

让我们创建一个使用多态计算不同形状面积的程序。我们将定义一个父类 Shape,以及重写 area 方法的子类 Circle 和 Rectangle。

代码:

# Defines the Shape parent class with an area method
class Shape:
    def area(self):
        pass  # Placeholder method

# Defines the Circle child class inheriting from Shape
class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius  # Sets the radius of the circle

    def area(self):
        return 3.14 * self.radius ** 2  # Calculates area of the circle

# Defines the Rectangle child class inheriting from Shape
class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width    # Sets the width of the rectangle
        self.height = height  # Sets the height of the rectangle

    def area(self):
        return self.width * self.height  # Calculates area of the rectangle

# Creates objects of Circle and Rectangle classes
circle = Circle(5)
rectangle = Rectangle(4, 6)

# Calculates and prints areas using polymorphism
print("Circle Area:", circle.area())        # Output: Circle Area: 78.5
print("Rectangle Area:", rectangle.area())  # Output: Rectangle Area: 24
# Defines the Vehicle parent class with a move method
class Vehicle:
    def move(self):
        print("The vehicle moves.")

# Defines the Bicycle child class inheriting from Vehicle
class Bicycle(Vehicle):
    def move(self):
        print("The bicycle pedals forward.")

# Defines the Airplane child class inheriting from Vehicle
class Airplane(Vehicle):
    def move(self):
        print("The airplane flies in the sky.")

# Creates objects of Bicycle and Airplane classes
bike = Bicycle()
plane = Airplane()

# Calls the move method on both objects
bike.move()
plane.move()

做得很好!

您已经了解了 Python 中的多态,以及它如何让不同类的对象以独特的方式响应相同的方法调用。多态可以增强代码的灵活性和可扩展性,使代码更易于管理和扩展。请继续练习,创建更多利用多态行为的类和方法,以加深理解!

多态 — 插图 10

常见问题解答

「多态」课时是免费的吗?

是的 — 「多态」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Python For Kids 课程的其余内容,请升级到 CoddyKit PRO。 Python For Kids 课程共包含 5 节课。

「多态」这节课中我会学到什么?

探索高级面向对象编程概念。 你通过在浏览器中直接运行的动手代码来练习 Python For Kids,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Python For Kids 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Python For Kids 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 5 节课,共 5 节。

「多态」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Python For Kids 课中编写并运行代码吗?

能。每节 Python For Kids 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 面向对象编程简介
  2. 创建类与对象
  3. 继承
  4. 封装
  5. 多态
← 返回 Python For Kids