问题描述
sum
是 Python 中的一个内置函数,所以这就是我得到这个输出的原因.
但是当我这样做时,
>>>类型(打印)它回来了
文件",第 1 行类型(打印)^语法错误:无效语法
那么,有没有打印类型?print
是 type()
函数的例外吗?
我使用的是 Python 2.7
在 Python 2 中,print
是一个语句,它与变量或函数完全不同.语句不是可以传递给 type()
的 Python 对象;它们只是语言本身的一部分,甚至比内置函数更重要.例如,您可以执行 sum = 5
(即使您不应该这样做),但您不能执行 print = 5
或 if = 7
因为 print
和 if
是语句.
在 Python 3 中,print
语句被替换为 print()
函数.因此,如果您执行 type(print)
,它将返回 .
奖励:
在 Python 2.6+ 中,您可以将 from __future__ import print_function
放在脚本的顶部(作为第一行代码),print
语句将是替换为 print()
函数.
sum
is a builtin function in Python, so that's why I get this output.
>>> type(sum)
<type 'builtin_function_or_method'>
But when I do,
>>> type(print)
It returns
File "<stdin>", line 1
type(print)
^
SyntaxError: invalid syntax
So, is there no type of print? Is print
an exception to the type()
function?
I am using Python 2.7
In Python 2, print
is a statement, which is a whole different kind of thing from a variable or function. Statements are not Python objects that can be passed to type()
; they're just part of the language itself, even more so than built-in functions. For example, you could do sum = 5
(even though you shouldn't), but you can't do print = 5
or if = 7
because print
and if
are statements.
In Python 3, the print
statement was replaced with the print()
function. So if you do type(print)
, it'll return <class 'builtin_function_or_method'>
.
BONUS:
In Python 2.6+, you can put from __future__ import print_function
at the top of your script (as the first line of code), and the print
statement will be replaced with the print()
function.
>>> # Python 2
>>> from __future__ import print_function
>>> type(print)
<type 'builtin_function_or_method'>
这篇关于Python中的打印类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!