python - 在 python 的 __str__ 方法中返回或打印

标签 python

在我卡住的多项选择题中,有三个选项。 问题来了:

以下哪项是 _str_method 的定义?

1. def __str__(self):
      print "(%s, %s, %s)" % (self._n, self._p, self._b)

2. def __str__(self):
      return "(%s, %s, %s)" % (self._n, self._p, self._b)

3. Both

我测试了他们两个,都有效,但据说 (2) 是答案。

所有其他类似问题的答案也都说带有'print'的功能不正确。

答案错了吗?

谢谢

最佳答案

来自 the official documentation (强调我的):

object.__str__(self)

Called by the str() built-in function and by the print statement to compute the “informal” string representation of an object. This differs from __repr__() in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object.

由于第一个版本没有返回字符串对象,所以一定是错误的。

关于python - 在 python 的 __str__ 方法中返回或打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13394046/

相关文章:

python - 如何在python中的其他两个字符串之间提取一个字符串?

python - Keras U-Net 加权损失实现

python - 保存 tiff 堆栈时如何指定颜色图

python - Pynput 键盘记录器仅返回 Shift、Command、空格和 Capslock 键

python - 无法从已保存的较高批量大小的模型中恢复批量大小 1 的权重以进行预测

python - xml.etree.ElementTree.ParseError : not well-formed (invalid token) 错误

java - 使用原始 python 包而不是 jython 包

python - 如何有条件地修改 numpy 多维数组的每个元素?

python - 在 scikit learn 中组合随机森林模型

python - 为什么 Python 会返回负面列表索引?