当前位置: 首页 > news >正文

多态取代条件表达式举例

# 使用多态的实现
from abc import ABC, abstractmethodclass Shape(ABC):@abstractmethoddef calculate_area(self):passclass Circle(Shape):def __init__(self, radius):self.radius = radiusdef calculate_area(self):return 3.14 * self.radius ** 2class Rectangle(Shape):def __init__(self, width, height):self.width = widthself.height = heightdef calculate_area(self):return self.width * self.heightclass Triangle(Shape):def __init__(self, base, height):self.base = baseself.height = heightdef calculate_area(self):return 0.5 * self.base * self.height# 使用示例
circle = Circle(5)
rectangle = Rectangle(4, 6)
triangle = Triangle(3, 7)# 统一调用方式
shapes = [circle, rectangle, triangle]
for shape in shapes:print(f"{type(shape).__name__} 面积: {shape.calculate_area()}")

反例
这种实现方式存在一些缺点,比如代码冗长,每次新增一种形状都需要修改 calculate_area 函数,这违背了开闭原则

# 使用条件表达式的实现
class Shape:def __init__(self, shape_type, **kwargs):self.shape_type = shape_typeself.kwargs = kwargsdef calculate_area(shape):if shape.shape_type == "circle":radius = shape.kwargs.get("radius")return 3.14 * radius ** 2elif shape.shape_type == "rectangle":width = shape.kwargs.get("width")height = shape.kwargs.get("height")return width * heightelif shape.shape_type == "triangle":base = shape.kwargs.get("base")height = shape.kwargs.get("height")return 0.5 * base * heightelse:raise ValueError("未知形状")# 使用示例
circle = Shape("circle", radius=5)
rectangle = Shape("rectangle", width=4, height=6)
triangle = Shape("triangle", base=3, height=7)print(f"圆形面积: {calculate_area(circle)}")
print(f"矩形面积: {calculate_area(rectangle)}")
print(f"三角形面积: {calculate_area(triangle)}")
http://www.xdnf.cn/news/1036261.html

相关文章:

  • 【Photoshop】使用置换将字体和背景融为一体
  • flask JWT 认证
  • 了解Redis的使用
  • 【AS32系列MCU调试教程】性能优化:Eclipse环境下AS32芯片调试效率提升
  • CSS预编译语言less
  • 键盘按键枚举 Key 说明文档
  • iOS swiftUI的实用举例
  • 人工智能学习15-Numpy-花式索引和索引技巧
  • linux常用基础命令_新
  • Java 数据类型选择题
  • 使用大模型预测短暂性脑缺血发作(TIA)的全流程系统技术方案大纲
  • Python Flask 框架学习笔记
  • Linux操作系统之运维常用命令
  • 华为OD机试_2025 B卷_字符串分割(Python,100分)(附详细解题思路)
  • aflplusplus:开源的模糊测试工具!全参数详细教程!Kali Linux教程!(四)
  • 22 - PSA模块
  • 解惑1、为何大容量电容滤低频,小容量电容滤高频
  • 数据库资源帖
  • 同旺科技 USB TO SPI / I2C适配器(专业版)--EEPROM读写——A
  • 代码随想录算法训练营day4
  • (15)python+ selenium自动化测试 - 回顾2
  • 采用微服务的预期收益是什么?我们如何衡量成功?
  • 大IPD之——学习华为市场洞察,为战略找到方向(四)
  • FastGPT实战:从0搭建AI知识库与MCP AI Agent系统
  • Java求职者面试题解析:Spring、Spring Boot、MyBatis框架与源码原理
  • SpringBoot自动化部署实战指南
  • 【Photoshop】使用内容识别去除水印文字
  • Vue3 + TypeScript + Element Plus 表格实例null检查方法
  • Java设计题:如何设计一个线程池
  • 浅拷贝 与 深拷贝