What is __repr__ function?

__repr__ function :
  • The __repr__ function returns a string representation of a Python object that may be evaluated by the Python interpreter to instantiate another instance of the object.
  • Called by the repr() built-in function and by string conversions (reverse quotes) to compute the "official" string representation of an object.
  • repr() tries to convert everything into a string that can be used with eval() to re-generate the original object.
  • repr() generates a computer friendly output.
  • str() is used by print() function to generate a user-friendly output.
  • str()'s output may or may not be used with eval().

>>> eval("'Hello'")
'Hello'

>>> eval('Hello')
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    eval('
Hello')
  File "<string>", line 1, in <module>
NameError: name '
Hello' is not defined

Comments

Popular posts from this blog

What is composite key?

What are the different data types in Python?