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
42
在 a
被求值之前打印。 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/