[英]How to print an object's representation using the string format function?
我正在創建一個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
你可以給你的班級一個__format__
方法 ; 在這種情況下只需調用重寫版本:
def __format__(self, spec):
spec = spec or ',.2f' # set a default spec when not explicitly given
return '$' + super().__format__(spec)
從鏈接的文檔:
由
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.