為什么要講 __repr__
在 Python 中,直接 print 一個實例對象,默認是輸出這個對象由哪個類創建的對象,以及在內存中的地址(十六進制表示)
假設在開發調試過程中,希望使用 print 實例對象時,輸出自定義內容,就可以用 __repr__ 方法了
或者通過 repr() 調用對象也會返回 __repr__ 方法返回的值
是不是似曾相識....沒錯..和 __str__ 一樣的感覺 代碼栗子
1
2
3
4
5
6
7
8
9
10
11
12
|
class A: pass def __repr__( self ): a = A() print (a) print ( repr (a)) print ( str (a)) # 輸出結果 <__main__.A object at 0x10e6dbcd0 > <__main__.A object at 0x10e6dbcd0 > <__main__.A object at 0x10e6dbcd0 > |
默認情況下,__repr__() 會返回和實例對象 <類名 object at 內存地址> 有關的信息
重寫 __repr__ 方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
class PoloBlog: def __init__( self ): self .name = "小菠蘿" self .add = "https://www.cnblogs.com/poloyy/" def __repr__( self ): return "test[name=" + self .name + ",add=" + self .add + "]" blog = PoloBlog() print (blog) print ( str (blog)) print ( repr (blog)) # 輸出結果 test[name = 小菠蘿,add = https: / / www.cnblogs.com / poloyy / ] test[name = 小菠蘿,add = https: / / www.cnblogs.com / poloyy / ] test[name = 小菠蘿,add = https: / / www.cnblogs.com / poloyy / ] |
只重寫 __repr__ 方法,使用 str() 的時候也會生效哦
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class PoloBlog: def __init__( self ): self .name = "小菠蘿" self .add = "https://www.cnblogs.com/poloyy/" def __str__( self ): return "test[name=" + self .name + ",add=" + self .add + "]" blog = PoloBlog() print (blog) print ( str (blog)) print ( repr (blog)) # 輸出結果 test[name = 小菠蘿,add = https: / / www.cnblogs.com / poloyy / ] test[name = 小菠蘿,add = https: / / www.cnblogs.com / poloyy / ] <__main__.PoloBlog object at 0x10e2749a0 > |
只重寫 __str__ 方法的話,使用 repr() 不會生效的哦!
str() 和 repr() 的區別
http://www.jfrwli.cn/article/74063.html
以上就是Python面向對象編程repr方法示例詳解的詳細內容,更多關于Python面向對象編程repr的資料請關注服務器之家其它相關文章!
原文鏈接:https://blog.csdn.net/qq_33801641/article/details/120232632