gpt4 book ai didi

python - 嵌套函数如何在 Python 中工作?

转载 作者:IT老高 更新时间:2023-10-28 20:25:32 25 4
gpt4 key购买 nike

def maker(n):
def action(x):
return x ** n
return action

f = maker(2)
print(f)
print(f(3))
print(f(4))

g = maker(3)
print(g(3))

print(f(3)) # still remembers 2

为什么嵌套函数记住第一个值 2 即使 maker() 已经返回并在 action() 时退出叫什么?

最佳答案

你基本上是在创建一个 closure .

In computer science, a closure is a first-class function with free variables that are bound in the lexical environment. Such a function is said to be "closed over" its free variables.

相关阅读:Closures: why are they so useful?

A closure is simply a more convenient way to give a function access to local state.

来自 http://docs.python.org/reference/compound_stmts.html :

Programmer’s note: Functions are first-class objects. A 'def' form executed inside a function definition defines a local function that can be returned or passed around. Free variables used in the nested function can access the local variables of the function containing the def. See section Naming and binding for details.

关于python - 嵌套函数如何在 Python 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2005956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com