為什么要講 __str__
- 在 Python 中,直接 print 一個實例對象,默認是輸出這個對象由哪個類創建的對象,以及在內存中的地址(十六進制表示)
- 假設在開發調試過程中,希望使用 print 實例對象時,輸出自定義內容,就可以用 __str__ 方法了
- 或者通過 str() 調用對象也會返回 __str__ 方法返回的值
重點
必須返回字符串
不使用 __str__ 的栗子
class PoloBlog: def __init__(self, name): self.name = name blog1 = PoloBlog("小菠蘿") print(blog1) # 輸出結果 <__main__.PoloBlog object at 0x1078a4dc0>
新增 __str__ 方法
class PoloBlog: def __init__(self, name): self.name = name def __str__(self): return "name is %s" % self.name blog1 = PoloBlog("小菠蘿") print(blog1) print(str(blog1)) # 輸出結果 name is 小菠蘿 name is 小菠蘿