2011-09-20 137 views
16

在python中,repr和反引號`(1的左邊)之間有區別嗎?Python:repr與反引號

出於演示:

class A(object): 
    def __repr__(self): 
     return 'repr A' 
    def __str__(self): 
     return 'str A' 


>>> a = A() 

>>> repr(a) 
#'repr A' 

>>> `a` 
#'repr A' 

>>> str(a) 
#'str A' 

不要反引號只需要調用repr?僅僅是爲了方便嗎?有沒有顯着的速度差異?

謝謝!

+2

重複http://stackoverflow.com/questions/1673071/what-do-backticks-mean-to-the-python-interpreter-num? – AlG

+1

爲什麼你會擔心速度差異? –

+1

@NedBatchelder,主要是爲了好奇。 – TorelTwiddler

回答

23

它們是repr的別名。它們具有完全相同的效果。

但是,它們已被棄用,並已在Python 3中刪除。請勿使用它們;使用repr