[英]Why does print with and without parentheses give __str__() and __repr__() in
[英]python why does it call __str__ instead of __repr__ and why is the print(obj) not working and throws exception
我有一個小問題,因為每當我在 try/except 部分運行代碼 print(obj) 時,它都會引發異常。 我使用調試工具跟蹤它,它直接跳轉到str方法中,但我編寫了str方法只是為了測試。 通常我認為它會跳轉到普通類調用的repr方法中。 代碼在str () 方法的返回命令中正確中斷。 我只是想更改 time.time_struct 類的輸出,因為我需要字符串和屬性表示。 打印命令僅用於顯示結果, init語句中的塊有效,但在 try/Except 塊中不起作用。 有沒有人有想法?
import time
class timeSelf():
def __init__(self,str):
self.obj = time.strptime(str, "%H:%M")
print(self.obj.tm_hour)
print(type(self.obj))
def __repr__(self):
return "" + self.obj.tm_hour + ":" + self.obj.tm_min
def __str__(self):
return "" + self.obj.tm_hour + ":" + self.obj.tm_min
if __name__ == "__main__":
str= "16:54"
try:
obj = timeSelf(str)
print(obj)
print(type(obj))
print(type(obj.tm_hour))
except Exception:
print("stuff happened")
pass
如果你沒有捕捉到的異常(或者,如果你重新提出它看到你抓到了什么),你會看到的問題是在你的定義__str__
和__repr__
。 您正在嘗試將int
和""
值與+
結合使用,並且那里不會發生int
到str
自動轉換。
Traceback (most recent call last):
File "tmp.py", line 19, in <module>
print(obj)
File "tmp.py", line 13, in __str__
return "" + self.obj.tm_hour + ":" + self.obj.tm_min
TypeError: can only concatenate str (not "int") to str
你必須明確:
return "" + str(self.obj.tm_hour) + ":" + str(self.obj.tm_min)
或更簡單地說:
return f"{self.obj.tm_hour}:{self.obj.tm_min}"
f-strings確實__str__
根據需要調用__str__
以將{...}
的值轉換為str
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.