Nested Scopes and Lambdas

我只是一个虾纸丫 提交于 2019-12-13 14:06:18

问题


def funct():
    x = 4
    action = (lambda n: x ** n)
    return action

x = funct()
print(x(2)) # prints 16

... I don't quite understand why 2 is assigned to n automatically?


回答1:


n is the argument of the anonymous function returned by funct. An exactly equivalent defintion of funct is

def funct():
    x = 4
    def action(n):
        return x ** n
    return action

Does this form make any more sense?




回答2:


It's not assigned "automatically": it's assigned very explicitly and non-automatically by your passing it as the actual argument corresponding to the n parameter. That complicated way to set x is almost identical (net of x.__name__ and other minor introspective details) to def x(n): return 4**n.



来源:https://stackoverflow.com/questions/2004398/nested-scopes-and-lambdas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!