Python中__str__和__repr_之间有什么区别?
当前回答
基本上__str__或str()用于创建人类可读的输出,这些输出必须面向最终用户。另一方面,repr()或__repr_主要返回对象的规范字符串表示,用于调试和开发,帮助程序员。
其他回答
需要记住的一点是,容器的__str__使用包含的对象的__repr_。
>>> from datetime import datetime
>>> from decimal import Decimal
>>> print (Decimal('52'), datetime.now())
(Decimal('52'), datetime.datetime(2015, 11, 16, 10, 51, 26, 185000))
>>> str((Decimal('52'), datetime.now()))
"(Decimal('52'), datetime.datetime(2015, 11, 16, 10, 52, 22, 176000))"
Python比可读性更倾向于明确性,元组的__str__调用调用所包含对象的__repr_,即对象的“形式”表示。虽然正式表示比非正式表示更难理解,但它是明确的,并且对bug更为健壮。
repr()用于调试或日志。它用于开发人员理解代码。另一方面,str()用户用于非开发人员(QA)或用户。
class Customer:
def __init__(self,name):
self.name = name
def __repr__(self):
return "Customer('{}')".format(self.name)
def __str__(self):
return f"cunstomer name is {self.name}"
cus_1 = Customer("Thusi")
print(repr(cus_1)) #print(cus_1.__repr__())
print(str(cus_1)) #print(cus_1.__str__())
__str__必须返回字符串对象,而__repr_可以返回任何python表达式。如果缺少__str__实现,则__repr_函数用作回退。如果缺少__repr_函数实现,则没有回退。如果__repr_函数返回对象的String表示,我们可以跳过__str__函数的实现。
资料来源:https://www.journaldev.com/22460/python-str-repr-functions
简而言之:
class Demo:
def __repr__(self):
return 'repr'
def __str__(self):
return 'str'
demo = Demo()
print(demo) # use __str__, output 'str' to stdout
s = str(demo) # __str__ is used, return 'str'
r = repr(demo) # __repr__ is used, return 'repr'
import logging
logger = logging.getLogger(logging.INFO)
logger.info(demo) # use __str__, output 'str' to stdout
from pprint import pprint, pformat
pprint(demo) # use __repr__, output 'repr' to stdout
result = pformat(demo) # use __repr__, result is string which value is 'str'
除非您特别采取行动以确保其他情况,否则大多数类对以下两种情况都没有帮助:
>>> class Sic(object): pass
...
>>> print(str(Sic()))
<__main__.Sic object at 0x8b7d0>
>>> print(repr(Sic()))
<__main__.Sic object at 0x8b7d0>
>>>
正如您所看到的,没有区别,也没有超出类和对象id的信息。如果您只覆盖这两个中的一个…:
>>> class Sic(object):
... def __repr__(self): return 'foo'
...
>>> print(str(Sic()))
foo
>>> print(repr(Sic()))
foo
>>> class Sic(object):
... def __str__(self): return 'foo'
...
>>> print(str(Sic()))
foo
>>> print(repr(Sic()))
<__main__.Sic object at 0x2617f0>
>>>
如您所见,如果重写__repr_,那么它也用于__str__,但反之亦然。
要知道的其他关键提示:内置容器上的__str__使用__repr_而不是__str__来表示它包含的项。而且,尽管在典型的文档中找到了关于这个主题的单词,但几乎没有人会将__repr_对象设置为eval可以用来构建相等对象的字符串(这太难了,而且不知道相关模块是如何实际导入的,这实际上是不可能的)。
因此,我的建议是:专注于使__str__合理地具有可读性,并尽可能地明确__repr___,即使这会干扰模糊的不可实现的目标,即使__repr_的返回值可接受作为__eval___的输入!
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录