1. 程式人生 > >Python 的 __str__ 和 __repr__ 方法比較

Python 的 __str__ 和 __repr__ 方法比較

閱讀到 Strings 中關於轉換物件為字串的內容,介紹了 repr 函式,趁著還沒有真正瞭解 Python 面向物件的生疏與熱度,感性上理解一下 repr 與 str 這兩個函式的區別。

Python 的全域性方法 repr 和 str 會對映到物件的 __repr__ 和 __str__ 的方法呼叫,還有 str(obj) 時會呼叫哪個方法,以及 print(obj) 和除錯 Python 程式碼時的物件顯示會呼叫哪個方法呢?這就是本文想要印證的內容。

恰如 Java 的 System.out.println(obj) 或 "hello" + obj 都會呼叫 Java 物件的 toString()

 方法,那麼 Python 中是怎麼一回事呢?

來自某本 Python 入門書的解釋 repr 和 str:

  1. reprformal string representation of a Python object
  2. strinformal string representation of a Python object,或者說 printable string representation

首先 repr 是 representation 的意思,一個是正式,另一個是非正式,看起來 repr 比 str 顯得重要些。 閱讀全文 >>