刘心向学(37)__repr__ 与 __str__:深入理解对象的字符串表示

boyanx13小时前技术教程2

分享兴趣,传播快乐,

增长见闻,留下美好!

亲爱的您,这里是LearningYard新学苑。

今天小编为大家带来文章

“刘心向学(37):__repr__ 与 __str__:深入理解对象的字符串表示

Share interest, spread happiness,

Increase knowledge, leave a beautiful!

Dear, this is LearningYard Academy.

Today, the editor brings you an article.

Liu Xinxiangxue (37): __repr__ vs __str__: Understanding Object String Representation in Python

Welcome to your visit.

一、思维导图(Mind Map

二、引言( Introduction

在 Python 中,当我们打印一个对象,或者将其转换为字符串时,Python 会调用该对象的 __str____repr__ 方法。虽然这两个方法看起来功能相似,但它们在用途和设计哲学上有明显区别。

In Python, when we print an object or convert it to a string, Python calls the object's __str__ or __repr__ method. Although these two methods seem similar in functionality, they differ significantly in purpose and design philosophy.

本文将带你深入理解 __str____repr__ 的区别、使用场景、默认行为,并通过多个示例说明如何在实际开发中合理使用它们。

This article will help you deeply understand the differences between __str__ and __repr__, their usage scenarios, default behaviors, and demonstrate how to use them effectively in real-world development through multiple examples.


三、基本概念(Basic Concepts)

简单类比:

Simple Analogy:

__str__ 是给 用户看的



__repr__ 是给 开发者或解释器看的

__str__ is for end users.

__repr__is for developers or the interpreter.


四、默认行为对比(Default Behavior Comparison)

我们来看一个默认行为的例子:

Let's look at an example of the default behavior:

Python深色版本classPerson:
def__init__(self, name, age):
        self.name = name
        self.age = age

p = Person("Alice", 30)
print(p)

输出类似:

The output may look like:

深色版本<__main__.Person object at 0x00000123456789>

这是默认的 __repr__(同时也是 __str__)输出,只显示对象类型和内存地址。

This is the default __repr__ (and also __str__ if not defined) output, showing only the object type and memory address.


五、示例对比(Example Comparison)

Python深色版本classBook:
def__init__(self, title, author):
        self.title = title
        self.author = author

def__str__(self):
returnf"{self.title} by {self.author}"

def__repr__(self):
returnf"Book(title='{self.title}', author='{self.author}')"

测试输出:

Test Output:

Python深色版本b = Book("Python编程", "Guido van Rossum")
print(b)               # 输出: Python编程 by Guido van Rossum (调用 __str__)
print(repr(b))         # 输出: Book(title='Python编程', author='Guido van Rossum') (调用 __repr__)

六、__repr__的“可执行”原则(The "Executable" Principle of __repr__)

理想情况下,__repr__ 返回的字符串应该是一个有效的 Python 表达式,可以直接复制粘贴到解释器中重建该对象。

Ideally, the string returned by __repr__ should be a valid Python expression that can be copied and pasted into the interpreter to recreate the object.

例如:

For example:

Python深色版本repr(b)  # "Book(title='Python编程', author='Guido van Rossum')"

如果类的构造函数支持这种写法,那么调试时会非常方便。

If the class constructor supports this syntax, it will be very convenient during debugging.


七、与 __format__的关系(Relationship with __format__)

除了 __str____repr__,还有一个魔法方法 __format__,用于支持 format() 函数和 f-string 的格式化输出。

In addition to __str__ and __repr__, there is another magic method __format__, which supports formatted output for the format() function and f-strings.

Python深色版本def__format__(self, format_spec):
if format_spec == 'short':
return self.title
elif format_spec == 'long':
returnf"{self.title} 作者:{self.author}"
else:
returnstr(self)

使用方式:

Usage:

Python深色版本print(f"{b:short}")   # 输出: Python编程
print(f"{b:long}")    # 输出: Python编程 作者:Guido van Rossum

八、结语(Conclusion)

__str____repr__ 是 Python 中用于控制对象字符串表示的两个魔法方法。虽然它们功能相似,但在用途、设计目标和使用场景上有着本质区别。

__str__ and __repr__ are two magic methods in Python used to control the string representation of objects. Although they are functionally similar, they differ fundamentally in purpose, design goals, and usage scenarios.

合理实现这两个方法,不仅能提升类的可读性和调试效率,还能增强代码的健壮性和用户体验。无论你是开发面向用户的程序,还是构建底层库或框架,理解并善用 __str____repr__ 都是一项非常有价值的能力。

Properly implementing these two methods can not only improve class readability and debugging efficiency but also enhance code robustness and user experience. Whether you are developing user-facing applications or building low-level libraries or frameworks, understanding and effectively using __str__ and __repr__ is a highly valuable skill.


今天的分享就到这里了。

如果您对文章有独特的想法,

欢迎给我们留言,

让我们相约明天。

祝您今天过得开心快乐!

That's all for today's sharing.

If you have a unique idea about the article,

please leave us a message,

and let us meet tomorrow.

I wish you a nice day!

参考资料:通义千问

参考文献:Beazley, D., & Jones, B. K. (2019). Python Cookbook (3rd ed.). O'Reilly Media.

Hettinger, R. (2019). Transforming Code into Beautiful, Idiomatic Python. PyCon US.

本文由LearningYard新学苑整理发出,如有侵权请在后台留言沟通!


LearningYard新学苑

文字:song

排版:song

审核|qiu

相关文章

Python学不会来打我(8)字符串string类型深度解析

2025年全球开发者调查显示,90%的Python项目涉及字符串处理,而高效使用字符串可提升代码效率40%。本文系统拆解字符串核心操作,涵盖文本处理、数据清洗、模板生成等八大场景,助你掌握字符串编程精...

Windows中CMD最全命令行(cmd命令行在哪)

CMD命令:开始->运行(或者Windows+R)->键入cmd或command(在命令行里可以看到系统版本、文件系统版本)CMD命令锦集1. gpedit.msc-----组策略2. s...

打钱专业户!330穿的八级金币黑枪王

大家好,我是你们的游戏小编:冴之木七星在八级,提起黑枪,大家第一个想到的可能还是莱茵(菜田),但是要说最强黑枪车,我Strv S1第一个不服。毕竟:这是一台只为黑枪而生的黑枪车!极高的隐蔽,超高的穿深...

AI 编码史诗级翻车现场!刚刚,Replit 一键删光客户整个生产数据库,官方连夜补锅

整理|冬梅策划|Tina1 网友痛斥 Replit AI 失控,删除了他们整个数据库昨夜,一位 X ID 名为 Jason 的用户发帖痛斥开发协作平台 Replit 在数据库事故处理中的混乱表现,引发...

【超测前瞻】涅槃重生,这一世它是全能铲车王!

前言虽拥有大威力大口径主炮,但S系VIII级坦歼“库斯特工程”的表现并不如意,甚至在整个“液压攻城坦歼”家族当中,它的表现都要相对靠后。时光悄然流逝,库斯特工程已是边缘过气坦,它之前另一位早早进入超测...

Java中你知道几种从字符串中找指定的字符的数量

遇到这样的问题,常规的思路估计就是遍历String,然后逐个对比。下面先看循环遍历循环遍历private static int getNum(String originStr, String targ...

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。