為什么要講 __repr__
在 Python 中,直接 print 一個(gè)實(shí)例對(duì)象,默認(rèn)是輸出這個(gè)對(duì)象由哪個(gè)類(lèi)創(chuàng)建的對(duì)象,以及在內(nèi)存中的地址(十六進(jìn)制表示)
假設(shè)在開(kāi)發(fā)調(diào)試過(guò)程中,希望使用 print 實(shí)例對(duì)象時(shí),輸出自定義內(nèi)容,就可以用 __repr__ 方法了
或者通過(guò) repr() 調(diào)用對(duì)象也會(huì)返回 __repr__ 方法返回的值
是不是似曾相識(shí)....沒(méi)錯(cuò)..和 __str__ 一樣的感覺(jué) 代碼栗子
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)) # 輸出結(jié)果 <__main__.A object at 0x10e6dbcd0 > <__main__.A object at 0x10e6dbcd0 > <__main__.A object at 0x10e6dbcd0 > |
默認(rèn)情況下,__repr__() 會(huì)返回和實(shí)例對(duì)象 <類(lèi)名 object at 內(nèi)存地址> 有關(guān)的信息
重寫(xiě) __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)) # 輸出結(jié)果 test[name = 小菠蘿,add = https: / / www.cnblogs.com / poloyy / ] test[name = 小菠蘿,add = https: / / www.cnblogs.com / poloyy / ] test[name = 小菠蘿,add = https: / / www.cnblogs.com / poloyy / ] |
只重寫(xiě) __repr__ 方法,使用 str() 的時(shí)候也會(huì)生效哦
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)) # 輸出結(jié)果 test[name = 小菠蘿,add = https: / / www.cnblogs.com / poloyy / ] test[name = 小菠蘿,add = https: / / www.cnblogs.com / poloyy / ] <__main__.PoloBlog object at 0x10e2749a0 > |
只重寫(xiě) __str__ 方法的話(huà),使用 repr() 不會(huì)生效的哦!
str() 和 repr() 的區(qū)別
http://www.zmynmublwnt.cn/article/74063.html
以上就是Python面向?qū)ο缶幊蘲epr方法示例詳解的詳細(xì)內(nèi)容,更多關(guān)于Python面向?qū)ο缶幊蘲epr的資料請(qǐng)關(guān)注服務(wù)器之家其它相關(guān)文章!
原文鏈接:https://blog.csdn.net/qq_33801641/article/details/120232632