在我卡住的多项选择题中,有三个选项。 问题来了:
以下哪项是 _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__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/