|
发表于 2024-12-31 18:02:57
|
显示全部楼层
- from decimal import Decimal
- exchange_rate = {
- "CNYUSD": Decimal(7.299),
- "USDCNY": Decimal(0.137),
- "CNYEUR": Decimal(7.625),
- "EURCNY": Decimal(0.131),
- "CNYJPY": Decimal(0.046),
- "JPYCNY": Decimal(21.59),
- }
- class Money:
- def __init__(self, value=0, kind='CNY'):
- if kind not in ['CNY', 'USD', 'JPY']:
- raise TypeError('请输入正确货币类型!')
- self.value = Decimal(value)
- self.kind= kind
- def exchange(self, kind):
- if kind not in ['CNY', 'USD', 'JPY']:
- raise TypeError('请输入正确货币类型!')
- return Money(value = self.value*exchange_rate[kind+self.kind], kind = kind)
- def __add__(self, other):
- if self.kind == other.kind:
- return Money(self.value+other.value, self.kind)
- return self+other.exchange(self.kind)
- def __sub__(self, other):
- if self.kind == other.kind:
- return Money(self.value-other.value, self.kind)
- return self+other.exchange(self.kind)
- def __str__(self):
- return str(float(self.value)) + ' ' + self.kind
复制代码 |
|