Python 中多态性的示例和类的继承多态性

单词 "多态" 意味着 "多种形式",在编程中,它指的是具有相同名称的方法/函数/操作符,可以在许多不同的对象或类上执行。

函数多态性

一个示例是 Python 中的 len() 函数,它可以用于不同的对象。

字符串

对于字符串,len() 返回字符的数量:

示例

python 复制代码
x = "Hello World!"

print(len(x))

元组

对于元组,len() 返回元组中项的数量:

示例

python 复制代码
mytuple = ("apple", "banana", "cherry")

print(len(mytuple))

字典

对于字典,len() 返回字典中键/值对的数量:

示例

python 复制代码
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

print(len(thisdict))

类的多态性

多态性通常在类的方法中使用,其中我们可以具有相同方法名称的多个类。例如,假设我们有三个类:Car、Boat 和 Plane,它们都有一个名为 move() 的方法:

示例

不同类具有相同的方法:

python 复制代码
class Car:
  def __init__(self, brand, model):
    self.brand = brand
    self.model = model

  def move(self):
    print("Drive!")

class Boat:
  def __init__(self, brand, model):
    self.brand = brand
    self.model = model

  def move(self):
    print("Sail!")

class Plane:
  def __init__(self, brand, model):
    self.brand = brand
    self.model = model

  def move(self):
    print("Fly!")

car1 = Car("Ford", "Mustang")       # 创建一个 Car 类
boat1 = Boat("Ibiza", "Touring 20") # 创建一个 Boat 类
plane1 = Plane("Boeing", "747")     # 创建一个 Plane 类

for x in (car1, boat1, plane1):
  x.move()

看看最后的 for 循环。由于多态性,我们可以为所有三个类执行相同的方法。

继承类的多态性

那么具有相同名称的子类的类呢?我们能在那里使用多态吗?如果我们使用上面的示例,并创建一个名为 Vehicle 的父类,并将 Car、Boat 和 Plane 作为 Vehicle 的子类,子类将继承 Vehicle 的方法,但可以重写它们:

示例,创建一个名为 Vehicle 的类,使 Car、Boat 和 Plane 成为 Vehicle 的子类:

python 复制代码
class Vehicle:
  def __init__(self, brand, model):
    self.brand = brand
    self.model = model

  def move(self):
    print("Move!")

class Car(Vehicle):
  pass

class Boat(Vehicle):
  def move(self):
    print("Sail!")

class Plane(Vehicle):
  def move(self):
    print("Fly!")

car1 = Car("Ford", "Mustang") # 创建一个 Car 对象
boat1 = Boat("Ibiza", "Touring 20") # 创建一个 Boat 对象
plane1 = Plane("Boeing", "747") # 创建一个 Plane 对象

for x in (car1, boat1, plane1):
  print(x.brand)
  print(x.model)
  x.move()

最后

为了方便其他设备和平台的小伙伴观看往期文章:公众号搜索Let us Coding,或者扫描下方二维码,关注公众号,即可获取最新文章。

看完如果觉得有帮助,欢迎点赞、收藏关注

相关推荐
玉鸯18 分钟前
Agent Hook:在概率推理之上,为 Agent 叠加确定性控制
python·langchain·agent
weixin_446260851 小时前
HACO:面向动态部署环境的对冲式智能计算可靠多智能体调度框架
后端·python·flask
我的xiaodoujiao1 小时前
API 接口自动化测试详细图文教程学习系列32--Allure测试报告2
python·学习·测试工具·pytest
qetfw2 小时前
MXU:Tauri 2 + React 的 MaaFramework 跨平台 GUI 源码
前端·python·react.js·前端框架·开源项目·效率工具
ttwuai2 小时前
Cursor 生成 CRUD 后,Go 后台接口别只测 200:JWT、RBAC 和 tenant_id 怎么验
开发语言·后端·golang
用户8356290780512 小时前
Python 实现 Excel 页面布局与打印设置自动化
后端·python
用户9931441579842 小时前
微服务框架中获取用户信息
后端
一次旅行3 小时前
Python+大模型端到端自动化日报系统
开发语言·python·自动化