双括号在函数调用中是什么意思?例如func(stuff)(stuff)? [英] What do double parentheses mean in a function call? e.g. func(stuff)(stuff)?
问题描述
原始标题:
Original title:
" 帮我理解这个奇怪的Python习语吗? sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
"Help me understand this weird Python idiom? sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
"
我一直使用这个惯用法来打印一堆内容,以Python 2的utf-8标准输出。*:
I use this idiom all the time to print a bunch of content to standard out in utf-8 in Python 2.*:
sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
但是老实说,我不知道(sys.stdout)
在做什么。这让我想起了Java语言关闭之类的东西。但是我不知道如何在Python文档中查找这个习惯用法。
But to be honest, I have no idea what the (sys.stdout)
is doing. It sort of reminds me of a Javascript closure or something. But I don't know how to look up this idiom in the Python docs.
你们中的任何一个人都可以解释这里发生了什么吗?谢谢!
Can any of you fine folks explain what's going on here? Thanks!
推荐答案
.getwriter
返回函数点击>可调用对象;您只是在同一行中调用它。
.getwriter
returns a functioncallable object; you are merely calling it in the same line.
示例:
def returnFunction():
def myFunction():
print('hello!')
return myFunction
Demo:
>>> returnFunction()()
hello!
您也可以选择:
>>> result = returnFunction()
>>> result()
hello!
可视化:
Visualization:
evaluation step 0: returnSomeFunction()()
evaluation step 1: |<-somefunction>-->|()
evaluation step 2: |<----result-------->|
这篇关于双括号在函数调用中是什么意思?例如func(stuff)(stuff)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!