Python repr() 函数用于获取对象的字符串表示。
此函数对于调试和日志记录目的很有用,因为与 str() 函数相比,它提供了对象的详细和清晰的表示。虽然 str() 主要用于创建人类可读的字符串,但 repr() 提供了一个字符串,当传递给 eval() 函数时,可以重新创建原始对象。
语法
以下是 Python repr() 函数的语法 -
repr(x)
参数
此函数将对象 'x' 作为要获取字符串表示的参数。
返回值
此函数返回一个字符串,当作为 Python 代码执行时,该字符串将重新创建原始对象。
示例 1在下面的示例中,我们使用 repr() 函数来获取字符串对象 “Hello, World!” 的字符串表示形式 -
text = "Hello, World!"
representation = repr(text)
print('The string representation obtained is:',representation)
输出
以下是上述代码的输出 -
The string representation obtained is: 'Hello, World!'
示例 2
在这里,我们使用 repr() 函数来获取整数对象 “42” 的字符串表示 -
number = 42
representation = repr(number)
print('The string representation obtained is:',representation)
输出
上述代码的输出如下 -
The string representation obtained is: 42
示例 3
在这里,我们获得了列表 “[1, 2, 3]” 的字符串表示。输出是一个字符串,当在 Python 代码中使用时,它将重新创建原始列表 -
my_list = [1, 2, 3]
representation = repr(my_list)
print('The string representation obtained is:',representation)
输出
获得的结果如下所示 -
The string representation obtained is: [1, 2, 3]
示例 4
在这种情况下,repr() 函数与复数 “(2+3j)” 一起使用 -
complex_num = complex(2, 3)
representation = repr(complex_num)
print('The string representation obtained is:',representation)
输出
以下是上述代码的输出 -
The string representation obtained is: (2+3j)
示例 5
在此示例中,我们定义了一个名为 “Point” 的自定义类,该类具有 “x” 和 “y” 属性来表示坐标。此外,我们在类中实现了一个 “repr” 方法来自定义字符串表示。之后,我们创建一个名为 “point_instance” 的类实例,坐标为 “(1, 2)”。通过使用 repr() 函数,我们获得格式化字符串 “Point(1, 2)” ,表示点的坐标 -
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f'Point({self.x}, {self.y})'
point_instance = Point(1, 2)
representation = repr(point_instance)
print('The string representation obtained is:',representation)
输出
生成的结果如下 -
The string representation obtained is: Point(1, 2)