Jes*_*s H 4 python string-formatting python-3.x
我正在创建一个Money类,我想将对象直接传递给字符串format()函数,并获得带有2位小数和货币符号的货币表示.
我应该用什么方法覆盖用字符串格式函数打印?覆盖str和repr不起作用.
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
Run Code Online (Sandbox Code Playgroud)
你可以给你的班级一个__format__方法 ; 在这种情况下只需调用重写版本:
def __format__(self, spec):
spec = spec or ',.2f' # set a default spec when not explicitly given
return '$' + super().__format__(spec)
Run Code Online (Sandbox Code Playgroud)
从链接的文档:
由
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
Run Code Online (Sandbox Code Playgroud)