How to print the representation of an object using the string formatting function?

I am creating a Money class, and I would like to pass the object directly to the string format () function and get a monetary representation with two decimal places and a currency symbol.

Which method should be overridden for printing using the line formatting function? Overriding str and repr does not work.

from decimal import Decimal


class Money(Decimal):
    def __str__(self):
        return "$" + format(self, ',.2f')

    def __repr__(self):
        return "$" + format(self, ',.2f')

m = Money("123.44")
print(m) # $123.44. Good.
m        # $123.44. Good.
print("Amount: {0}".format(m)) # 123.44. Bad. I wanted $123.44
print(f"Amount: {m}") # 123.44. Bad. I wanted $123.44
+4
source share
1 answer

You can give your class a method __format__; in this case, just call the overridden version:

def __format__(self, spec):
    spec = spec or ',.2f'  # set a default spec when not explicitly given
    return '$' + super().__format__(spec)

From related documentation:

format() , str.format(), "" . format_spec - , . format_spec __format__(), , .

__str__ __repr__ , , '$' , __format__ ( format(self, ...)).

:

>>> from decimal import Decimal
>>> class Money(Decimal):
...     def __format__(self, spec):
...         spec = spec or ',.2f'  # set a default spec when not explicitly given
...         return '$' + super().__format__(spec)
...
>>> m = Money("123.44")
>>> print("Amount: {0}".format(m))
Amount: $123.44
>>> print(f"Amount: {m}")
Amount: $123.44
+9

Source: https://habr.com/ru/post/1695914/


All Articles