简体   繁体   English

Python - 从 float 继承并调用 str 和 repr 时出现递归错误

[英]Python - recursion error when inherit from float and call str and repr

I was testing some features in Python for fun;) But I have a recursion error that I don't understand为了好玩,我正在测试 Python 中的一些功能;)但是我有一个我不明白的递归错误

class Test(float):
    def __new__(cls, value):
        return super().__new__(cls, value)

    def __str__(self):
        return super().__str__()
    
    def __repr__(self):
        return f'<value: {str(self)}>'


test = Test(12)
test

the return super().__str__() should call float.__str__() and just returns '12' return super().__str__()应该调用float.__str__()并且只返回 '12'

Do you have any ideas?你有什么想法?

Your __repr__ calls your __str__ , which calls the super's __str__ , which defers to repr , which calls your __repr__ , which is an infinite recursion.你的__repr__调用你的__str__ ,它调用超级的__str__ ,它遵循repr ,它调用你的__repr__ ,这是一个无限递归。 You could call super().__repr__ in your __repr__ method, instead of calling str(self) .您可以在__repr__方法中调用super().__repr__ ,而不是调用str(self)

class Test(float):
    def __new__(cls, value):
        return super().__new__(cls, value)

    def __str__(self):
        return super().__str__()
    
    def __repr__(self):
        return f'<value: {super().__repr__()}>'
>>> Test(12)
<value: 12.0>

The core issue is that float.__str__(self) will call self.__repr__() rather than float.__repr__(self) .核心问题是float.__str__(self)将调用self.__repr__()而不是float.__repr__(self)

Not only does that mean that you have an infinite recursion from Test.__repr__ to Test.__str__ to float.__str__ back to Test.__repr__ , it means that Test.__str__ is going to print the same thing as Test.__repr__ , which I assume you don't want since you went to the effort of reimplementing it.这不仅意味着您有从Test.__repr__Test.__str__float.__str__Test.__repr__ .__repr__ 的无限递归,这意味着Test.__str__将打印与Test.__repr__相同的东西,我假设你不想要,因为你努力重新实现它。

Instead I think you want:相反,我认为你想要:

class Test(float):
    def __str__(self):
        return super().__repr__()
    
    def __repr__(self):
        return f'<value: {super().__repr__()}>'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM