Python repr()函数
Python repr()函数返回传递给它的对象的可打印表示。
句法:
repr(object)
参数:
object : The object whose printable representation is to be returned.
返回值:
Returns a string.
可以在类中定义 __repr__() 方法来控制此函数为其对象返回的内容。
示例 1:将字符串对象传递给 repr 方法
Python3
strObj = 'geeksforgeeks'
print(repr(strObj))
Python3
num = {1, 2, 3, 4, 5}
# printable representation of the set
printable_num = repr(num)
print(printable_num)
Python3
class geek:
def __init__(self, name):
self.name = name
# defining __repr__() method to control what
# to return for objects of geek
def __repr__(self):
return self.name
geek1 = geek('mohan')
print(repr(geek1))
输出
'geeksforgeeks'
示例 2:将 set 对象传递给 repr 方法
Python3
num = {1, 2, 3, 4, 5}
# printable representation of the set
printable_num = repr(num)
print(printable_num)
输出
{1, 2, 3, 4, 5}
示例 3:在类中定义 __repr__() 方法
Python3
class geek:
def __init__(self, name):
self.name = name
# defining __repr__() method to control what
# to return for objects of geek
def __repr__(self):
return self.name
geek1 = geek('mohan')
print(repr(geek1))
输出
mohan
解释:
类中定义了repr(),特殊方法返回对象的name属性,创建geek类的对象并将字符串传递给它,字符串的可打印表示为print。