为什么不能将python的print分配给变量? [英] Why can't I assign python's print to a variable?

查看:100
本文介绍了为什么不能将python的print分配给变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习编程,并且正在使用Python进行启动.在那儿,我看到我可以做这样的事情:

I'm learning to program and I am using Python to start. In there, I see that I can do something like this:

>>>> def myFunction(): return 1
>>>> test = myFunction
>>>> test()
1

但是,如果我尝试对print执行相同操作,则会失败:

However, if I try and do the same with print it fails:

>>>> test2 = print
File "<stdin>", line 1
  test2 = print
              ^
SyntaxError: invalid syntax

为什么print与我创建的函数不同?这是使用Python v2.7.5.

Why is print different than a function I create? This is using Python v2.7.5.

推荐答案

print是一个语句,而不是函数. 在Python 3中进行了更改,部分原因是允许您执行此类操作.在Python 2.7中,您可以通过在文件顶部执行from __future__ import print_function来获得打印功能,然后您就可以执行test = print.

print is a statement, not a function. This was changed in Python 3 partly to allow you to do things like this. In Python 2.7 you can get print as a function by doing from __future__ import print_function at the top of your file, and then you will indeed be able to do test = print.

请注意,使用print作为功能,您不能再执行print x,而必须执行print(x)(即,需要括号).

Note that with print as a function, you can no longer do print x but must do print(x) (i.e., parentheses are required).

这篇关于为什么不能将python的print分配给变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆