什么是Python中的'print'?

时间:2011-08-11 03:12:24

标签: python

我理解print的作用,但语言元素的“类型”是什么?我认为这是一个功能,但为什么会失败?

>>> print print
SyntaxError: invalid syntax

print不是一个功能吗?不应该打印这样的东西吗?

>>> print print
<function print at ...>

5 个答案:

答案 0 :(得分:63)

在2.7及以下,print是一个陈述。在python 3中,print是一个函数。要在Python 2.6或2.7中使用print函数,可以执行

>>> from __future__ import print_function
>>> print(print)
<built-in function print>

请参阅Python语言参考中的this section,以及PEP 3105更改原因。

答案 1 :(得分:35)

在Python 3中,print()是一个内置函数(对象)

在此之前,print声明。示范...

Python 2. x

% 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<-----

Python 3. x

% 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.

答案 2 :(得分:21)

print是一个在Python 3中已经纠正的错误。在Python 3中它是一个函数。在Python 1.x和2.x中,它不是一个函数,它是一个特殊的形式,如ifwhile,但与这两个不同,它不是一个控制结构。

所以,我想最准确的说法就是陈述。

答案 3 :(得分:7)

在Python中,所有语句(赋值除外)都用保留字表示,而不是可寻址对象。这就是为什么你不能简单地print print并且你得到SyntaxError来尝试。这是一个保留词,而不是一个对象。

令人困惑的是,您可以拥有名为print的变量。您无法以正常方式解决问题,但您可以setattr(locals(), 'print', somevalue)然后print locals()['print']

其他保留字可能是变量名称但仍然是禁止的:

class
import
return
raise
except
try
pass
lambda

答案 4 :(得分:1)

在Python 2中,print是一个语句,它与变量或函数完全不同。语句不是可以传递给type()的Python对象;它们只是语言本身的一部分,甚至比内置函数更重要。例如,您可以执行sum = 5(即使您不应该这样做),但您不能print = 5if = 7因为print和{{if 1}}是陈述。

在Python 3中,print语句被print()函数替换。因此,如果您执行type(print),则会返回<class 'builtin_function_or_method'>

<强>奖金:

在Python 2.6+中,您可以将from __future__ import print_function放在脚本的顶部(作为第一行代码),print语句将替换为print()函数

>>> # Python 2
>>> from __future__ import print_function
>>> type(print)
<type 'builtin_function_or_method'>