When __repr__() is called?

前端 未结 4 1014
轻奢々
轻奢々 2021-01-17 10:08

print OBJECT calls OBJECT.__str__(), then when OBJECT.__repr__() is called? I see that print OBJECT calls OBJECT.__

相关标签:
4条回答
  • 2021-01-17 10:52

    repr(obj) calls obj.__repr__.

    This is intended to clearly describe an object, specially for debugging purposes. More info in the docs

    0 讨论(0)
  • 2021-01-17 10:54

    Not only does __repr__() get called when you use repr(), but also in the following cases:

    1. You type obj in the shell and press enter
    2. You ever print an object in a dictionary/tuple/list. E.g.: print [u'test'] does not print ['test']
    0 讨论(0)
  • 2021-01-17 10:55
    repr(obj)
    

    calls

    obj.__repr__
    

    the purpose of __repr__ is that it provides a 'formal' representation of the object that is supposed to be a expression that can be evaled to create the object. that is,

    obj == eval(repr(obj))
    

    should, but does not always in practice, yield True

    I was asked in the comments for an example of when obj != eval(repr(obj)).

    class BrokenRepr(object):
        def __repr__(self):
            return "not likely"
    

    here's another one:

    >>> con = sqlite3.connect(':memory:')
    >>> repr(con)
    '<sqlite3.Connection object at 0xb773b520>'
    >>> 
    
    0 讨论(0)
  • 2021-01-17 11:07

    In python 2.x, `obj` will end up calling obj.__repr__(). It's shorthand for repr().

    0 讨论(0)
提交回复
热议问题