Python provides many built-in functions that are part of the Python language and can be used directly in Python programs without importing any modules.
This series will gradually organize and share some of the Python built-in functions.
There are two ways to obtain the accompanying code for this article:
- Get it via Baidu Cloud:
Link: https://pan.baidu.com/s/11x9_wCZ3yiYOe5nVcRk2CQ?pwd=mnsj Extraction code: mnsj
- Visit GitHub to obtain:
https://github.com/returu/Python_built-in_functions
01Introduction: The repr
() function is used to return a string that represents the printable form of an object. This string is mainly used during the development and debugging phases, as it is designed to allow developers to clearly see the representation of the object. The string is usually interpretable, and in many cases, the original object can be restored using the eval()
function.
The basic syntax of the <span>repr()</span>
function is as follows:
repr(object)
Parameter Description:
- object: Any Python object.
Return Value:
<span>repr()</span>
function returns a string that represents the printable form of the object.
02Usage:
Here are some examples of using the repr() function:
-
Example 1:
For many built-in types, the string returned by repr() usually has valid Python syntax, allowing it to be passed to the eval() function to generate an object equivalent to the original object.
# Built-in types
print(repr(42)) # Output: '42'
print(repr("hello")) # Output: '"hello"'
print(repr([1, 2, 3])) # Output: '[1, 2, 3]'
print(repr({'a': 1})) # Output: '{'a': 1}'
x = [1, 2, 3]
x == eval(repr(x))
# Output: True
- Example 2:
For custom classes, if a specific __repr__() method is not defined, repr() will return a string surrounded by angle brackets. This string includes the type name of the object and some identification information (such as memory address).
class MyClass:
pass
obj = MyClass()
print(repr(obj))
# Output: <__main__.MyClass object at 0x000001B22680FA70>
- Example 3:
For custom classes, you can control the return value of repr() by defining the __repr__() method. This method should return a string that represents the object in a way that is useful for debugging and development.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point(x={self.x}, y={self.y})"
p = Point(1, 2)
print(repr(p))
# Output: 'Point(x=1, y=2)'