简体   繁体   中英

__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() . It is used by repr() , str() (if __str__ is not defined). You shouldn't call __repr__ explicitly.

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:

>>>> 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:

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

All it does is call the object's __repr__() function. I'm not sure why anyone would need to call the object's __repr__() method explicitly. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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