我对 float 进行了子类化以更改其 __str__()
方法以一个符号结尾(在我的例子中为 €)。
输入被过滤以删除一个符号(在我的例子中是 €)。
class Euro(float):
def __new__(cls, value):
v = ''.join([_ for _ in value if _ != '€' ])
return super(Euro, cls).__new__(cls, v)
def __str__(self):
return f'{self} €'
但是当我打印时,出现递归打印错误。
g = Euro('123.23 €')
print (g)
错误:
Euro.py, line __str__
return f'{self} €'
[Previous line repeated 329 more times]
RecursionError: maximum recursion depth exceeded
最佳答案
使用super()
调用父类的方法,避免递归错误。
def __str__(self):
return super().__str__() + ' €'
>>> g = Euro('123.23 €')
>>> print(g)
123.23 €
关于python - float 子类以改变摄入量和 __str__ 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60360569/