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

posted @   chuangzhou  阅读(54)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2022-11-09 Git - 错误集
2022-11-09 pytest - 测试报告
2022-11-09 Chrome - network 最低端栏位解释
点击右上角即可分享
微信分享提示