我知道 print
做了什么,但它是哪种语言元素的"类型"呢?我认为它是一个函数,但为什么会失败呢?
>>> print print
SyntaxError: invalid syntax
print
不是函数吗?它难道不应该打印出类似这样的东西吗?
>>> print print
<function print at ...>
我知道 print
做了什么,但它是哪种语言元素的"类型"呢?我认为它是一个函数,但为什么会失败呢?
>>> print print
SyntaxError: invalid syntax
print
不是函数吗?它难道不应该打印出类似这样的东西吗?
>>> print print
<function print at ...>
print()
是一个内置函数(对象)。print
是一个语句。演示...
% pydoc2.6 print
The ``print`` statement
***********************
print_stmt ::= "print" ([expression ("," expression)* [","]]
| ">>" expression [("," expression)+ [","]])
``print`` evaluates each expression in turn and writes the resulting
object to standard output (see below). If an object is not a string,
it is first converted to a string using the rules for string
conversions. The (resulting or original) string is then written. A
space is written before each object is (converted and) written, unless
the output system believes it is positioned at the beginning of a
line. This is the case (1) when no characters have yet been written
to standard output, (2) when the last character written to standard
output is a whitespace character except ``' '``, or (3) when the last
write operation on standard output was not a ``print`` statement. (In
some cases it may be functional to write an empty string to standard
output for this reason.)
-----8<-----
% pydoc3.1 print
Help on built-in function print in module builtins:
print(...)
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 print
在两种情况下都是错误的语法。 - Woobleprint()
需要括号。我在我的答案中包含了这些。 - johnsywebprint
是Python 3中已经纠正的错误。在Python 3中,它是一个函数。而在Python 1.x和2.x中,它不是一个函数,它类似于if
或while
这样的特殊形式,但与这两者不同的是,它不是一种控制结构。
因此,我想最准确地称它为语句。
print print
,并因尝试而得到SyntaxError
。它是一个保留字,而不是一个对象。setattr(locals(),'print',somevalue)
,然后使用print locals()['print']
。class
import
return
raise
except
try
pass
lambda
print
函数。 from __future__ import print_function
从模块中删除了“打印语句”解析,因此它不会干扰内置函数。 - Antti Haapala -- Слава Україніprint
是一个语句(statement),它与变量或函数完全不同。语句不是Python对象,不能传递给type()
;它们只是语言本身的一部分,甚至比内置函数还要重要。例如,你可以做sum = 5
(虽然不应该这样做),但你不能做print = 5
或if = 7
,因为print
和if
是语句。print
语句被print()
函数替换。因此,如果你执行type(print)
,它将返回<class 'builtin_function_or_method'>
。from __future__ import print_function
,这样print
语句就会被替换为print()
函数。>>> # Python 2
>>> from __future__ import print_function
>>> type(print)
<type 'builtin_function_or_method'>
print
可能是一个函数或语句 (语言结构),这取决于你所使用的 Python 的主要版本,但它绝对不是一个运算符。 - David Ferenczy Rogožan