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,或者扫描下方二维码,关注公众号,即可获取最新文章。

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

相关推荐
Lethehong20 分钟前
Python Selenium全栈指南:从自动化入门到企业级实战
python·selenium·测试工具·自动化
智算菩萨1 小时前
MP3音频编码原理深度解析与Python全参数调优实战:从心理声学模型到LAME编码器精细控制
android·python·音视频
wuyikeer1 小时前
Spring Framework 中文官方文档
java·后端·spring
Victor3561 小时前
MongoDB(61)如何避免大文档带来的性能问题?
后端
qq_452396231 小时前
【模型手术室】第四篇:全流程实战 —— 使用 LLaMA-Factory 开启你的第一个微调任务
人工智能·python·ai·llama
Victor3562 小时前
MongoDB(62)如何避免锁定问题?
后端
无心水2 小时前
Java时间处理封神篇:java.time全解析
java·开发语言·python·架构·localdate·java.time·java时间处理
wuyikeer2 小时前
Spring BOOT 启动参数
java·spring boot·后端
吴秋霖2 小时前
【某音电商】protobuf聊天协议逆向
python·算法·protobuf
深藏功yu名2 小时前
Day24:向量数据库 Chroma_FAISS 入门
数据库·人工智能·python·ai·agent·faiss·chroma