from __future__ import division
class BaseWallet:
def __init__(self, name, amount, exchange_rate=1):
self.name = f'{name}'
self.amount = amount
self.exchange_rate = exchange_rate
def __add__(self, other):
if isinstance(other, BaseWallet):
new_amount = self.amount + other.amount * other.exchange_rate/self.exchange_rate
else:
new_amount = self.amount + float(other)
return BaseWallet(self.name, new_amount, self.exchange_rate)
def __sub__(self, other):
if isinstance(other, BaseWallet):
new_amount = self.amount - other.amount * other.exchange_rate/self.exchange_rate
else:
new_amount = self.amount - float(other)
return BaseWallet(self.name, new_amount, self.exchange_rate)
def __mul__(self, other):
new_amount = self.amount * float(other)
return BaseWallet(self.name, new_amount, self.exchange_rate)
def __div__(self, other):
new_amount = self.amount / float(other)
return BaseWallet(self.name, new_amount, self.exchange_rate)
def __rmul__(self, other):
return BaseWallet.__mul__(self, other)
def __radd__(self, other):
return BaseWallet.__add__(self, other)
class RubleWallet(BaseWallet):
coef = 1
def __init__(self, name, amount, exchange_rate=coef):
self.name = f'{name}'
self.amount = amount
self.exchange_rate = exchange_rate
class DollarWallet(BaseWallet):
coef = 60
def __init__(self, name, amount, exchange_rate=coef):
self.name = f'{name}'
self.amount = amount
self.exchange_rate = exchange_rate
class EuroWallet(BaseWallet):
coef = 70
def __init__(self, name, amount, exchange_rate=coef):
self.name = f'{name}'
self.amount = amount
self.exchange_rate = exchange_rate
ob1 = RubleWallet("X", 70)
ob2 = EuroWallet("D", 10)
ob2 = ob2/5
print(ob2.name, ob2.amount, ob2.exchange_rate)
我将抛开程序的整个代码,因为这里通常会立即询问它。如您所见,已经实现了许多表示算术运算的魔术方法。注意div方法。所有方法都可以正常工作,但不是他。Pycharm 不像所有其他方法一样使它变成粉红色。它只是没有被定义为一种方法。执行下面写的行时,会出现以下错误:
D:\Documents\Pycharm\venv\Scripts\python.exe D:/Documents/Pycharm/task10.py
Traceback (most recent call last):
File "D:/Documents/Pycharm/task10.py", line 66, in <module>
ob2 = ob2/5
TypeError: unsupported operand type(s) for /: 'EuroWallet' and 'int'
我用谷歌搜索,到处都说div方法在 python 中。但是我的python不明白。Python 3.8 版。pycharm版本:
因为你需要使用
__truediv__().