[英]Possible to call single-parameter Python function without using parentheses?
The Python documentation specifies that is is legal to omit the parentheses if a function only takes a single parameter, but Python文档指定如果函数只接受单个参数,则省略括号是合法的,但是
myfunction "Hello!"
generates a syntax error. 生成语法错误。 So, what's the deal? 那么,这笔交易是什么?
(I'm using Python 3.1) (我正在使用Python 3.1)
EDIT: 编辑:
The statement that I read only applies to generator expressions : 我读的语句只适用于生成器表达式 :
The parentheses can be omitted on calls with only one argument.
For your edit: 为了您的编辑:
If you write down a generator expression, like stuff = (f(x) for x in items)
you need the brackets, just like you need the [ .. ]
around a list comprehension. 如果你写下一个生成器表达式,比如stuff = (f(x) for x in items)
你需要括号,就像你需要围绕列表理解的[ .. ]
。
But when you pass something from a generator expression to a function (which is a pretty common pattern, because that's pretty much the big idea behind generators) then you don't need two sets of brackets - instead of something like s = sum((f(x) for x in items))
(outer brackets to indicate a function call, inner for the generator expression) you can just write sum(f(x) for x in items)
但是当你将一些东西从生成器表达式传递给一个函数时(这是一个非常常见的模式,因为这几乎是生成器背后的重要思想)那么你不需要两组括号 - 而不是像s = sum((f(x) for x in items))
那样s = sum((f(x) for x in items))
东西s = sum((f(x) for x in items))
(外括号表示函数调用,内部表示生成器表达式)你可以只写sum(f(x) for x in items)
Without parentheses those wouldn't be functions
but statements
or keywords
(language-intrinsic). 没有括号,那些不是functions
而是statements
或keywords
(语言本征)。
This StackOverflow thread (with some very nice answers) contains a lead as to how one can create their own in pure Python (through advanced hackery, and not a good idea in 99.99% of the cases). 这个StackOverflow线程 (有一些非常好的答案) 包含一个关于如何在纯Python中创建自己的线索 (通过高级hackery,在99.99%的情况下不是一个好主意)。
As I understand the rule is only about the generator expressions... so for example: sum(x 2 for x in range(10)), but you would still have to write: reduce(operator.add, (x 2 for x in range(10))). 据我所知,规则只是关于生成器表达式...所以例如:sum(x 2表示范围(10)中的x),但你仍然需要写:reduce(operator.add,(x 2 for x)在范围(10)))。
This doesn't apply for generic functions though. 但这不适用于通用功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.