1. 程式人生 > >python 中的__str__ 和__repr__方法

python 中的__str__ 和__repr__方法

創建對象 交互 以及 程序 通過 統一 內部 cal Language

看下面的例子就明白了

class Test(object):
    def __init__(self, value=‘hello, world!‘):
        self.data = value

>>> t = Test()
>>> t
<__main__.Test at 0x7fa91c307190>
>>> print t
<__main__.Test object at 0x7fa91c307190>

# 看到了麽?上面打印類對象並不是很友好,顯示的是對象的內存地址
# 下面我們重構下該類的__repr__以及__str__,看看它們倆有啥區別

# 重構__repr__
class TestRepr(Test):
    def __repr__(self):
        return ‘TestRepr(%s)‘ % self.data

>>> tr = TestRepr()
>>> tr
TestRepr(hello, world!)
>>> print tr
TestRepr(hello, world!)

# 重構__repr__方法後,不管直接輸出對象還是通過print打印的信息都按我們__repr__方法中定義的格式進行顯示了

# 重構__str__
calss TestStr(Test):
    def __str__(self):
        return ‘[Value: %s]‘ % self.data

>>> ts = TestStr()
>>> ts
<__main__.TestStr at 0x7fa91c314e50>
>>> print ts
[Value: hello, world!]

# 你會發現,直接輸出對象ts時並沒有按我們__str__方法中定義的格式進行輸出,而用print輸出的信息卻改變了

__repr__和__str__這兩個方法都是用於顯示的,__str__是面向用戶的,而__repr__面向程序員。

  • 打印操作會首先嘗試__str__和str內置函數(print運行的內部等價形式),它通常應該返回一個友好的顯示。

  • __repr__用於所有其他的環境中:用於交互模式下提示回應以及repr函數,如果沒有使用__str__,會使用print和str。它通常應該返回一個編碼字符串,可以用來重新創建對象,或者給開發者詳細的顯示。

當我們想所有環境下都統一顯示的話,可以重構__repr__方法;當我們想在不同環境下支持不同的顯示,例如終端用戶顯示使用__str__,而程序員在開發期間則使用底層的__repr__來顯示,實際上__str__只是覆蓋了__repr__以得到更友好的用戶顯示。

python 中的__str__ 和__repr__方法