Python - !r
没有使用 !r:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f'Point({self.x}, {self.y})'
p = Point('1', '2')
print(repr(p)) # 输出:Point(1, 2)
p = Point(1, 2)
print(repr(p)) # 输出:Point(1, 2)
使用!r:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f'Point({self.x!r}, {self.y!r})'
p = Point('1', '2')
print(repr(p)) # 输出:Point('1', '2')
p = Point(1, 2)
print(repr(p)) # 输出:Point(1, 2)
!r是一种格式化字符串的方法,它的作用是将一个对象转换为其表示的字符串形式,并保留对象本身的表达方式。
https://geek-docs.com/python/python-ask-answer/67_python_what_does_r_do_in_str_and_repr.html
本文来自博客园,作者:chuangzhou,转载请注明原文链接:https://www.cnblogs.com/czzz/p/17823119.html