Python 浮动子类,以改变进水口和str行为
我对float进行了子分类,将其Python 浮动子类,以改变进水口和str行为,python,python-3.x,subclass,Python,Python 3.x,Subclass,我对float进行了子分类,将其\uu str\uu()方法改为以符号结尾(在我的例子中是€) 过滤输入以删除符号(在我的例子中为€) 但是当我打印时,我得到一个递归打印错误 g = Euro('123.23 €') print (g) 错误: Euro.py,行__ 返回f'{self}€' [上一行重复了329次] 递归错误:超过最大递归深度 使用super()调用父方法并避免递归错误 def __str__(self): return super().__str__() + '
\uu str\uu()
方法改为以符号结尾(在我的例子中是€)
过滤输入以删除符号(在我的例子中为€)
但是当我打印时,我得到一个递归打印错误
g = Euro('123.23 €')
print (g)
错误:
Euro.py,行__
返回f'{self}€'
[上一行重复了329次]
递归错误:超过最大递归深度
使用super()
调用父方法并避免递归错误
def __str__(self):
return super().__str__() + ' €'
>>> g = Euro('123.23 €')
>>> print(g)
123.23 €
不要使用继承;
Euro
不是一种float
,由于实数的浮点近似值不精确,货币永远不应该用float
s表示
相反,使用composition来存储一个表示欧元数量的属性,使用类似于decimal.decimal的东西来准确地表示欧元和美分
我得到了以下代码:
from decimal import Decimal
class Euro:
def __init__(self, value):
if isinstance(value, str):
value = value.strip(' €')
self.value = Decimal(value)
def __add__(self, other):
return Euro(self.value + other.value)
def __sub__(self,other):
return Euro(self.value - other.value)
def __str__(self):
return f'{self.value} €'
我不认为有必要分班。
我添加了对返回Euro对象的+/-运算符的支持
结果是:
g = Euro(1.00)
h = Euro('10.00 €')
print (h+g) # --> 11.00 €
print (h-g) # --> 9.00 €
from decimal import Decimal
class Euro:
def __init__(self, value):
if isinstance(value, str):
value = value.strip(' €')
self.value = Decimal(value)
def __add__(self, other):
return Euro(self.value + other.value)
def __sub__(self,other):
return Euro(self.value - other.value)
def __str__(self):
return f'{self.value} €'
g = Euro(1.00)
h = Euro('10.00 €')
print (h+g) # --> 11.00 €
print (h-g) # --> 9.00 €