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

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

相关推荐
她的男孩2 分钟前
加了 @Idempotent 还是重复扣款了 3 笔:扒完 1279 行幂等 Starter,我挖出 5 个隐蔽的坑
java·后端·架构
SunnyDays10113 分钟前
使用 Python 将 PowerPoint 转换为视频(无需安装 Microsoft PowerPoint)
python·powerpoint·ppt 转 动画·ppt 转 mp4·ppt 转 wmv·幻灯片转动画·幻灯片转 mp4
飞Link4 分钟前
零基础:离散数据积分与 Python 实现保姆级教程
python·算法
用户03321266636714 分钟前
使用 Python 将 PDF 转换为 Word(转换单个与多个文件)
python
troy12818 分钟前
Visual Studio Code 详细教程:从入门到高效开发
开发语言·python
夜雪一千24 分钟前
Python ASR音频转文本 完整代码示例
python
pe7er33 分钟前
引子
前端·后端·架构
SimonKing34 分钟前
阅后即焚的加密便签:Cryptgeon,你口袋里的秘密信使
java·后端·程序员
灯澜忆梦35 分钟前
【Redis中间件】#2 | 基础数据类型语法
redis·后端
JarmanYuo36 分钟前
YOLO 涨点研究(十二):具身 CV 进阶篇——Sim2Real 域随机化与真机部署
人工智能·pytorch·python·yolo·计算机视觉