Environment: python 2.x
If print
is a built-in function, why does it not behave like othe开发者_StackOverflow社区r functions ? What is so special about print
?
-----------start session--------------
>>> ord 'a'
Exception : invalid syntax
>>> ord('a')
97
>>> print 'a'
a
>>> print('a')
a
>>> ord
<built-in function ord>
>>> print
-----------finish session--------------
The short answer is that in Python 2, print
is not a function but a statement.
In all versions of Python, almost everything is an object. All objects have a type. We can discover an object's type by applying the type
function to the object.
Using the interpreter we can see that the builtin functions sum
and ord
are exactly that in Python's type system:
>>> type(sum)
<type 'builtin_function_or_method'>
>>> type(ord)
<type 'builtin_function_or_method'>
But the following expression is not even valid Python:
>>> type(print)
SyntaxError: invalid syntax
This is because the name print
itself is a keyword, like if
or return
. Keywords are not objects.
The more complete answer is that print
can be either a statement or a function depending on the context.
In Python 3, print
is no longer a statement but a function.
In Python 2, you can replace the print
statement in a module with the equivalent of Python 3's print
function by including this statement at the top of the module:
from __future__ import print_function
This special import is available only in Python 2.6 and above.
Refer to the documentation links in my answer for a more complete explanation.
print
in Python versions below 3, is not a function. There's a separate print statement which is part of the language grammar. print
is not an identifier. It's a keyword.
The deal is that print
is built-in function only starting from python 3 branch. Looks like you are using python2.
Check out:
print "foo"; # Works in python2, not in python3
print("foo"); # Works in python3
print is more treated like a keyword than a function in python. The parser "knows" the special syntax of print (no parenthesis around the argument) and how to deal with it. I think the Python creator wanted to keep the syntax simple by doing so. As maverik already mentioned, in python3 print is being called like any other function and a syntx error is being thrown if you do it the old way.
精彩评论