Python str & repr

Python str & repr

repr 更可能是用來配合 eval 的 (<- 點擊查看),str 更可能是用來轉換成字符串格式的html

str() & repr()

str() 和 repr() 都會返回一個字符串
可是 str() 返回的結果更加適合於人閱讀,repr() 返回的結果更適合解釋器讀取python

二者差別

示例:函數

string = 'Hello World'
print(str(string), len(str(string)))
print(repr(string), len(repr(string)))

輸出結果:命令行

Hello World 11
'Hello World' 13

說明 str() 返回的仍然是字符串自己,可是 repr() 返回的是帶引號的字符串code

__repr__ & __str__

在一個類中 __repr____str__ 均可以返回一個字符串htm

示例:
當類中同時有這兩個方法blog

class Test(object):
    def __init__(self):
        pass

    def __repr__(self):
        return 'from repr'

    def __str__(self):
        return 'from str'


test = Test()
print(test)
print(test.__repr__())
print(test.__str__())

輸出結果:字符串

from str
from repr
from str

當類中只有 __str__ 方法時get

class Test(object):
    def __init__(self):
        pass

    def __str__(self):
        return 'from str'


test = Test()
print(test)
print(test.__repr__())
print(test.__str__())

輸出結果:string

from str
<__main__.Test object at 0x105df89e8>
from str

當類中只有 __repr__ 方法時

class Test(object):
    def __init__(self):
        pass

    def __repr__(self):
        return 'from repr'


test = Test()
print(test)
print(test.__repr__())
print(test.__str__())

輸出結果:

from repr
from repr
from repr

說明 print() 函數調用的是 __str__ ,而命令行下直接輸出時調用的是 __repr__
當類中沒有 __str__ 時,會調用 __repr__ ,可是若是沒有 __repr__ ,並不會去調用 __str__

相關文章
相關標籤/搜索