python子类浮标,以更改摄入量和__str__的行为

问题描述 投票:0回答:1

我将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

我已经将浮点数子类化,以改变它的'str'方法,以一个符号(在我的情况下为€)结尾。对输入进行过滤以删除一个符号(在我的情况下为€)class Euro(float):def __new__ (cls,值):...

python python-3.x subclass
1个回答
0
投票

使用super()调用父级的方法并避免递归错误。

© www.soinside.com 2019 - 2024. All rights reserved.