这两种方法有区别吗?
例如,
from datetime import date
today = date(2012, 10, 13)
repr(today)
'datetime.date(2012, 10, 13);
today.__repr__()
'datetime.date(2012, 10, 13)'
Run Code Online (Sandbox Code Playgroud)
他们似乎做了同样的事情,但为什么有人想要在常规报告中使用后者呢?
jfs*_*jfs 10
__repr__方法用于实现自定义结果repr().它被使用repr(),str()(如果__str__没有定义).你不应该__repr__明确地打电话.
不同之处在于repr()强制将字符串作为返回的类型,并且repr()__repr__在类对象上查找,而不是实例本身:
>>>> class C(object):
.... def __repr__(self):
.... return 1 # invalid non-string value
....
>>>> c = C()
>>>> c.__repr__() # works
1
>>>> repr(c) # enforces the rule
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: __repr__ returned non-repr (type 'int')
>>>> c # calls repr() implicitly
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: __repr__ returned non-repr (type 'int')
>>>> str(c) # also uses __repr__
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: __str__ returned non-str (type 'int')
>>>> c.__repr__ = lambda: "a"
>>>> c.__repr__() # lookup on instance
'a'
>>>> repr(c) # old method from the class
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: __repr__ returned non-repr (type 'int')
>>>>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1230 次 |
| 最近记录: |