简体   繁体   English

__repr__ vs repr

[英]__repr__ vs repr

Is there a difference between the two methods? 这两种方法有区别吗?

For example, 例如,

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

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

They seem to do the same thing, but why would someone want to use the latter over the regular repr? 他们似乎做了同样的事情,但为什么有人想要在常规报告中使用后者呢?

__repr__ method is used to implement custom result for repr() . __repr__方法用于实现 repr()自定义结果。 It is used by repr() , str() (if __str__ is not defined). 它由repr()str() (如果__str__ )。 You shouldn't call __repr__ explicitly. 你不应该明确地调用__repr__

The difference is that repr() enforces the string as the returned type and repr() looks up __repr__ on a class object, not an instance itself: 区别在于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')
>>>>

It's the same thing 这是同一件事

Think of repr() as containing the following code: 可以将repr()视为包含以下代码:

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

All it does is call the object's __repr__() function. 它只是调用对象的__repr__()函数。 I'm not sure why anyone would need to call the object's __repr__() method explicitly. 我不确定为什么有人需要显式调用对象的__repr__()方法。 In fact, it's generally bad coding style to do so (it's confusing, and leads the programmer to ask questions like the one that you did just now). 事实上,这样做的编码风格通常很糟糕(令人困惑,并导致程序员提出类似你刚才所做的问题)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM