鱼C论坛

 找回密码
 立即注册
查看: 308|回复: 6

[类和对象] 【II】实现一个简单的货币运算系统

[复制链接]
发表于 2024-12-31 11:54:46 | 显示全部楼层 |阅读模式
购买主题 已有 2 人购买  本主题需向作者支付 5 鱼币 才能浏览
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2024-12-31 12:21:35 | 显示全部楼层
第一
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2024-12-31 18:02:57 | 显示全部楼层
  1. from decimal import Decimal

  2. exchange_rate = {
  3.     "CNYUSD": Decimal(7.299),
  4.     "USDCNY": Decimal(0.137),
  5.     "CNYEUR": Decimal(7.625),
  6.     "EURCNY": Decimal(0.131),
  7.     "CNYJPY": Decimal(0.046),
  8.     "JPYCNY": Decimal(21.59),
  9. }

  10. class Money:
  11.     def __init__(self, value=0, kind='CNY'):
  12.         if kind not in ['CNY', 'USD', 'JPY']:
  13.             raise TypeError('请输入正确货币类型!')
  14.         self.value = Decimal(value)
  15.         self.kind= kind

  16.     def exchange(self, kind):
  17.         if kind not in ['CNY', 'USD', 'JPY']:
  18.             raise TypeError('请输入正确货币类型!')
  19.         return Money(value = self.value*exchange_rate[kind+self.kind], kind = kind)

  20.     def __add__(self, other):
  21.         if self.kind == other.kind:
  22.             return Money(self.value+other.value, self.kind)
  23.         return self+other.exchange(self.kind)

  24.     def __sub__(self, other):
  25.         if self.kind == other.kind:
  26.             return Money(self.value-other.value, self.kind)
  27.         return self+other.exchange(self.kind)

  28.     def __str__(self):
  29.         return str(float(self.value)) + ' ' + self.kind
复制代码

点评

感觉自己对内置方法的运用还是不太熟练,中间又去翻了翻 decimal 的速查宝典  发表于 2024-12-31 18:04
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-12-31 21:18:40 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2024-12-31 21:19:35 | 显示全部楼层
加上爬虫获取实时汇率
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2025-1-1 20:04:39 | 显示全部楼层
11
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-10 16:38

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表