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 but RecursionError for repr().

  • Case 2a gives expected repr() output but unexpected str() output:

>>> str(storage)
'Storage(512.0, "GB") GB'
  • Case 2b gives RecursionError for both str() and repr().

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