__str__ 和 __repr__ 的目的是什么? [英] What is the purpose of __str__ and __repr__?

查看:44
本文介绍了__str__ 和 __repr__ 的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的不明白 Python 中的 __str____repr__ 在哪里使用.我的意思是,我知道 __str__ 返回对象的字符串表示.但我为什么需要那个?在什么用例场景中?另外,我阅读了 __repr__

I really don't understand where are __str__ and __repr__ used in Python. I mean, I get that __str__ returns the string representation of an object. But why would I need that? In what use case scenario? Also, I read about the usage of __repr__

但我不明白的是,我会在哪里使用它们?

But what I don't understand is, where would I use them?

推荐答案

__repr__

repr() 内置函数和字符串转换(反引号)调用以计算对象的官方"字符串表示.如果可能的话,这应该看起来像一个有效的 Python 表达式,可用于重新创建具有相同值的对象(给定适当的环境).

Called by the repr() built-in function and by string conversions (reverse quotes) to compute the "official" string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment).

__str__

str() 内置函数和打印语句调用以计算对象的非正式"字符串表示.

Called by the str() built-in function and by the print statement to compute the "informal" string representation of an object.

使用 __str__ 如果您有一个类,并且每当您将此对象用作字符串的一部分时,您都需要信息性/非正式输出.例如.您可以为 Django 模型定义 __str__ 方法,然后在 Django 管理界面中呈现这些方法.而不是像 <Model object> 这样的东西,你会得到一个人的名字和姓氏,事件的名字和日期等.

Use __str__ if you have a class, and you'll want an informative/informal output, whenever you use this object as part of string. E.g. you can define __str__ methods for Django models, which then gets rendered in the Django administration interface. Instead of something like <Model object> you'll get like first and last name of a person, the name and date of an event, etc.

__repr____str__ 很相似,实际上有时相等(来自 sets.py 中的 BaseSet 类的示例来自标准库):

__repr__ and __str__ are similar, in fact sometimes equal (Example from BaseSet class in sets.py from the standard library):

def __repr__(self):
    """Return string representation of a set.

    This looks like 'Set([<list of elements>])'.
    """
    return self._repr()

# __str__ is the same as __repr__
__str__ = __repr__

这篇关于__str__ 和 __repr__ 的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆