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

boyanx4个月前技术教程25

分享兴趣,传播快乐,

增长见闻,留下美好!

亲爱的您,这里是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

相关文章

算法系列:实现strStr函数(字符串)

28. 实现 strStr()描述给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则...

python进阶100集(6)深入分析字符串切片

以下是关于Python字符串切片及修改替换的深度解析,包含原理说明和典型操作示例:#python##python自学##python教程#一、字符串切片机制1. 切片基础语法str[start:...

三菱FX5U中字符串的查找与替换怎么用?(附程序案例)

今天我们来讲一下字符串的查找,当在通信过程中,我们收到的是一系列的字符串,我们要在一系列字符串中查找有用的信息并进行与协议对比,然后得出对比结果并进行相应的处理,字符串的查找一般会用在PLC与其他设...

C++基础——文件逐行读取与字符匹配

C++基础——文件逐行读取与字符匹配目录技术背景C++读取文件C++字符串匹配C++运行时间统计总结概要版权声明技术背景用惯了python,对其他语言就比较的生疏。但是python很多时候在性能上比较...

C#字符串处理黑科技:从O(n^2)到O(n),性能提升100倍!

在C#编程中,字符串处理是极为常见的操作。从简单的文本拼接,到复杂的文本解析与匹配,字符串处理的性能优劣对程序整体效率有着深远影响。许多开发者可能未曾察觉,一些看似常规的字符串处理方式,实际上隐藏着严...

【西门子】关于从S7-1200字符串中提取有效数值

PLC从上位机或智能设备读取到一组杂乱无章的字符数据,比如"A,1;22=333,5678,E.909" ,需要从这个字符串中把有用的数字提取出来(只提取数字,舍弃字母及标点),需要...

发表评论    

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