开发者

Nested Scopes and Lambdas

开发者 https://www.devze.com 2022-12-15 23:04 出处:网络
def funct(): x = 4 action = (lambda n: x ** n) return action x = funct() print(x(2开发者_如何学运维)) # prints 16
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?


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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消