Python的内置打印为什么/如何允许“>>"操作员? [英] Why/how does Python's print built-in allow the ">>" operator?
问题描述
我到处搜索,但无论是在本网站还是在其他地方都找不到答案(总是很难找到涉及标点符号的主题).
I searched around and couldn't find an answer to this either on this site or elsewhere (always a challenge searching for topics involving punctuation chars).
我在Python标准库(此处),其中一个示例是(摘录):
I was looking up the StringIO
in the Python standard library (here) and one of the examples is this (excerpt):
import StringIO
output = StringIO.StringIO()
output.write('First line.\n')
print >>output, 'Second line.' # <-- This is the line I'm asking about
>>
运算符在这里如何或为什么起作用?据我所知(而且我不是Python专家),这是正确的shift运算符.我以为也许StringIO
会覆盖__rshift__
之类的东西,但是StringIO的来源并没有出卖任何此类东西.
How or why does the >>
operator work here? As far as I can tell (and I'm no Python expert), this is the right shift operator. I thought perhaps StringIO
overrides __rshift__
or something, but the source for StringIO does not betray any such thing.
我还没有四处看看如何实现内置的print
,但是通过最初的搜索,我无法弄清楚它是如何工作的.有人吗?
I haven't poked around to see how the print
built-in is implemented yet, but with initial searching I'm unable to figure out how this works. Anyone?
推荐答案
这实际上是几个问题.
首先,如何"问题:
>>
令牌实际上不是此处的运算符;它是print
语句语法的一部分,如此处所述.语法是:
The >>
token is not actually an operator here; it's part of the syntax of the print
statement, as documented here. The grammar is:
print_stmt ::= "print" ([expression ("," expression)* [","]]
| ">>" expression [("," expression)+ [","]])
...的语义是:
这种形式有时也称为印刷人字形".以这种形式,
>>
之后的第一个表达式必须计算为文件状"对象,特别是具有如上所述的write()
方法的对象.通过这种扩展形式,后续表达式将打印到该文件对象.
This form is sometimes referred to as "print chevron." In this form, the first expression after the
>>
must evaluate to a "file-like" object, specifically an object that has awrite()
method as described above. With this extended form, the subsequent expressions are printed to this file object.
第二,为什么"问题:
Second, the "why" question:
早期,Python开发人员认为这是一种方便的写入文件的方式.
Early on, the Python developers thought this was a convenient way to write to files.
从那时起,他们添加了 stdout重定向,以及更强大的文件和字符串格式API,因此它不再有用.而且,由于关键字参数等其他现代功能,以及几十年来的思考,他们提出了一种更灵活的方法来设计
Since then, they've added stdout redirection, and more powerful file and string-formatting APIs, so it's not as useful anymore. And, thanks to other modern features like keyword arguments, and a few decades to think about it, they've come up with a more flexible way to design print
as a regular function that doesn't require any special syntax at all. But removing it would break backward compatibility, so it couldn't be removed until 3.0.
并且在3.0中将其删除;您仍然看到它,因为您使用的是旧版本.
And it was removed in 3.0; you're only still seeing it because you're using an older version.
If you want the new print
function in 2.7, however, you can use a future statement: from __future__ import print_function
. But that will of course break print >>foo, spam
; you'll have to rewrite it as print(spam, file=foo)
.
这篇关于Python的内置打印为什么/如何允许“>>"操作员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!