admin管理员组文章数量:1123082
The class below works as expected:
class Storage(float):
def __new__(cls, value, unit):
instance = super().__new__(cls, value)
instance.unit = unit
return instance
def __str__(self):
return f"{super().__repr__()} {self.unit}" # 1.
# return f"{super().__str__()} {self.unit}" # 2.
def __repr__(self):
return f'Storage({super().__repr__()}, "{self.unit}")' # a.
# return f'Storage({super().__str__()}, "{self.unit}")' # b.
I did not know which dunder method to call on super()
so I tried all variants, see commented lines. I thought they would all work since __str__()
and __repr__()
work the same for floats.
- Case 1a gives the desired output:
>>> storage = Storage(512, "GB")
>>> str(storage)
'512.0 GB'
>>> repr(storage)
'Storage(512.0, "GB")'
Case 1b gives expected
str()
output butRecursionError
forrepr()
.Case 2a gives expected
repr()
output but unexpectedstr()
output:
>>> str(storage)
'Storage(512.0, "GB") GB'
- Case 2b gives
RecursionError
for bothstr()
andrepr()
.
Can you please help me understand how these overridden methods get tangled up?
本文标签: Overriding str and repr magic methods for builtin float class in PythonStack Overflow
版权声明:本文标题:Overriding __str__ and __repr__ magic methods for built-in float class in Python - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736547036a1944461.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论