刘心向学(37)__repr__ 与 __str__:深入理解对象的字符串表示
分享兴趣,传播快乐,
增长见闻,留下美好!
亲爱的您,这里是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