gpt4 book ai didi

Python object.__repr__(self) 应该是一个表达式?

转载 作者:IT老高 更新时间:2023-10-28 21:37:07 28 4
gpt4 key购买 nike

我正在查看 Python documentation 中的内置对象方法。 ,我对 object.__repr__(self) 的文档很感兴趣。它是这样说的:

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). If this is not possible, a string of the form <...some useful description...> should be returned. The return value must be a string object. If a class defines repr() but not str(), then repr() is also used when an “informal” string representation of instances of that class is required.

This is typically used for debugging, so it is important that the representation is information-rich and unambiguous

对我来说最有趣的部分是......

If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value

...但我不确定这到底是什么意思。它说它应该看起来像一个可用于重新创建对象的表达式,但这是否意味着它应该只是你可以使用的那种表达式的一个例子,或者它应该是一个实际的表达式,可以执行(eval 等)来重新创建对象?或者...是否应该只是为了纯粹的信息目的而对所使用的实际表达进行重新设计?

总的来说,我对我应该在这里放什么感到有点困惑。

最佳答案

>>> from datetime import date
>>>
>>> repr(date.today()) # calls date.today().__repr__()
'datetime.date(2009, 1, 16)'
>>> eval(_) # _ is the output of the last command
datetime.date(2009, 1, 16)

输出是一个字符串,可以被python解释器解析并产生一个相等的对象。

如果这不可能,它应该以 <...some useful description...> 的形式返回一个字符串.

关于Python object.__repr__(self) 应该是一个表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/452300/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com