1. 程式人生 > >python關於物件的字串顯示str和repr以及

python關於物件的字串顯示str和repr以及

1.repr

object.__ repr__(self)
Called by the repr() built-in function to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <…some useful description…> should be returned. The return value must be a string object. If a class defines __ repr__() but not __ str__(), then __ repr__() is also used when an “informal” string representation of instances of that class is required.
This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.

被repr()函式呼叫來輸出物件的正式的字串表示,通常情況下,這種表示應該儘可能像有效的python表示式; 此方法的返回值必須是個字串;如果類中定義了repr但沒有定義str, 那需要非正式的字串表示時repr也會被使用; repr方法通常用於除錯.
物件在直譯器中的顯示內容就是通過repr來控制的.

見下例

>>>class Test:
    def __repr__(self):
        return 'hahaha'
t = Test()
>>>t
hahaha

>>>class Test1:
    pass
t1 = Test1() >>>t1 <Test1 object at 0x000001D7BE8B3668>

2.str

object.str(self)
Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object. The return value must be a string object.
This method differs from object.repr

() in that there is no expectation that str() return a valid Python expression: a more convenient or concise representation can be used.
The default implementation defined by the built-in type object calls object.repr().

被str(), format(), print()函式呼叫來輸出物件的 ‘非正式’ 字串表示; 返回值必須是個字串; 和repr不同的是不要求返回一個有效的python表示式, 所以返回一個方便清晰的字串是個不錯的選擇. 內建型別物件預設呼叫repr來顯示.
所以print()函式顯示內容呼叫的是str方法返回的結果

class Test2:
    def __str__(self):
        return 'hahaha'
    def __repr__(self):
        return 'enenen'
t2 = Test2()
>>>print(t2)
hahaha
>>>t2
enenen

3.format

object.__ format__(self, format_spec)
1)Called by the format() built-in function, and by extension, evaluation of formatted string literals and the str.format() method, to produce a “formatted” string representation of an object. The format_spec argument is a string that contains a description of the formatting options desired. The interpretation of the format_spec argument is up to the type implementing __ format__(), however most classes will either delegate formatting to one of the built-in types, or use a similar formatting option syntax.
2)See Format Specification Mini-Language for a description of the standard formatting syntax.
The return value must be a string object.

類的內建format方法被format()函式,以及通過擴充套件,評估格式化的字串文字的str.format()方法呼叫, 來生成物件的格式化字串顯示; format_spec引數是一個字串,包含所需的格式化選項的說明;,該方法必須返回一個字串.
但是大多數類會將格式化委託給其中一個內建型別,或者使用類似的格式化選項語法。(不是很懂)
下例為format的一個使用示例:

format_dic = {'123': '{0.year}{0.month}{0.day}',
              '321': '{0.day}{0.month}{0.year}'}
class Foo:
    def __format__(self, format_spec):
        print('format執行')
        if not format_spec or format_spec not in format_dic:
            format_spec = '123'
        f = format_dic[format_spec]
        return f.format(self)

    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

d = Foo('2018', '12', '20')
print(format(d, '321'))
#result
format執行
20122018