3

这两种方法有区别吗?

例如,

from datetime import date
today = date(2012, 10, 13)
repr(today)
'datetime.date(2012, 10, 13);

today.__repr__()
'datetime.date(2012, 10, 13)'

他们似乎做同样的事情,但为什么有人要使用后者而不是常规的 repr?

4

2 回答 2

11

__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')
>>>>
于 2012-10-13T22:53:55.043 回答
4

这是同一件事

认为repr()包含以下代码:

def repr(obj):
    return obj.__repr__()

它所做的只是调用对象的__repr__()函数。我不确定为什么有人需要__repr__()显式调用对象的方法。事实上,这样做通常是一种糟糕的编码风格(这会让人感到困惑,并导致程序员提出像你刚才所做的那样的问题)。

于 2012-10-13T22:34:18.323 回答