Python对象。repr(self)应该是表达式吗?

2024-04-27 04:44:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我在查看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等)来重新创建对象的实际表达式?或者。。。它是否应该仅仅是为了纯粹的信息目的而使用的实际表达式的重新解释?

总的来说,我有点搞不清楚我到底应该把什么放在这里。


Tags: ofthetoanstringifthatobject
3条回答

准则:如果您可以简洁地提供精确的表示形式,请将其格式化为Python表达式(这意味着可以在正确的上下文中对其进行求值并直接复制到源代码中)。如果提供不精确的表示,请使用<...>格式。

任何值都有许多可能的表示,但是对于Python程序员来说最有趣的是一个重新创建值的表达式。记住,理解Python的人是目标受众,这也是不精确表示应该包含相关上下文的原因。即使是默认的<XXX object at 0xNNN>,虽然几乎完全没有用处,但仍然提供类型id()(用于区分不同的对象),并指示没有更好的表示。

>>> 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表达式,当eval'd时,它将创建一个与此对象具有完全相同属性的对象。例如,如果有一个包含两个整数(分子和分母)的Fraction类,那么__repr__()方法如下所示:

# in the definition of Fraction class
def __repr__(self):
    return "Fraction(%d, %d)" % (self.numerator, self.denominator)

假设构造函数接受这两个值。

相关问题 更多 >