[轉]Python中__repr__和__str__區別

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__以獲得更友好的用戶顯示。來源:https://blog.csdn.net/luckytanggu/article/details/53649156
相關文章
相關標籤/搜索