Python built-in functions (53) -- repr, python built-in 53 repr
English document:
-
repr
(
Object)
-
Return a string containing a printable representation of an object. For polictypes, this function makes an attempt to return a string that wocould yield an object with the same value when passed
eval()
, Otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining
__repr__()
Method.
-
Note:
-
1. The function returns the string representation of an object. Its function is similar to the str function, but there is also a difference between the two: the str () function is used to convert the value into a form suitable for reading, while repr () converted to the form for the interpreter to read.
>>> a = 'some text'>>> str(a)'some text'>>> repr(a)"'some text'"
2. The results of the repr function can generally be obtained through the eval () Evaluate method to obtain the original object.
>>> eval(repr(a))'some text'
3. For a general type, the repr function called on its instance returns a string consisting of its type, defined module, and memory address.
>>> class Student: def __init__(self,name): self.name = name>>> a = Student('Bob')>>> repr(a)'<__main__.Student object at 0x037C4EB0>'
4. If you want to change the display information of the type repr function, you need to define the _ repr _ function in the type for control.
>>> class Student: def __init__(self,name): self.name = name def __repr__(self): return ('a student named ' + self.name)>>> b = Student('Kim')>>> repr(b)'a student named Kim'