python - print.__doc__ vs getattr(__builtin__ ,"print").__doc__

标签 python python-2.x

print.__doc__ 输出:

SyntaxError: invalid syntax

在哪里

>>> getattr(__builtin__,"print").__doc__

输出:

print(value, ..., sep=' ', end='\n', file=sys.stdout)

Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments:

file : a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.

谁能帮我理解为什么 print.__doc__ 给出语法错误而不是打印文档字符串

最佳答案

在 Python 2(或 Python < 2.6 非常准确)中 print 完全不像一个函数,因此没有文档字符串。它甚至不会在开始打印之前评估所有参数:

>>> print 42, a
42
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

42a 被求值之前打印。 print 是一个语句,它后面有 0 到 N 逗号分隔的表达式,可选地在构造 >> file 之前,构造 print.__doc__是非法的。它与 if.__doc__return.__doc__ 一样毫无意义。

但是从 Python 2.6 开始,print 函数__builtin__ 模块中可用,但默认情况下不作为 print statement 与它冲突,除非 print 语句的解析被 from __future__ import print_function 禁用。

关于python - print.__doc__ vs getattr(__builtin__ ,"print").__doc__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23951085/

相关文章:

python - 如何检查大型 python pandas 数据框是否有重复项(不需要实际的重复行)

python - 谷歌Foobar : Attribute Error when submitting solution

python - 使用python在Barchart网站上抓取表格

Python:如何按位将 4 位数字的数组转换为更大的数字?

python - 在 sklearn python 中撤消 L2 规范化

python - 如何访问 Celery AsyncResult 中的重试尝试

python - 如何堆叠元类

python - 如何创建一个 tkinter 切换按钮?

python - 如何确定创建闭包的函数?

python - 如何在同一客户端上处理两个版本的Python?