闭包

Python 函数编写

Shayne Miel

Software Architect @ Duo Security

将非局部变量附着到嵌套函数

def foo():
  a = 5
  def bar():
    print(a)
  return bar

func = foo()

func()
5

闭包!

type(func.__closure__)
<class 'tuple'>
len(func.__closure__)
1
func.__closure__[0].cell_contents
5
Python 函数编写

闭包与删除

x = 25

def foo(value):
  def bar():
    print(value)
  return bar

my_func = foo(x)
my_func()
25
del(x)
my_func()
25
len(my_func.__closure__)
1
my_func.__closure__[0].cell_contents
25
Python 函数编写

闭包与覆盖

x = 25

def foo(value):
  def bar():
    print(value)
  return bar

x = foo(x)
x()
25
len(x.__closure__)
1
x.__closure__[0].cell_contents
25
Python 函数编写

定义 - 嵌套函数

嵌套函数:定义在另一个函数内部的函数。

# outer function
def parent():
  # nested function
  def child():
    pass
  return child
Python 函数编写

定义 - 非局部变量

非局部变量(nonlocal):在父函数中定义、由子函数使用的变量。

def parent(arg_1, arg_2):
  # From child()'s point of view,
  # `value` and `my_dict` are nonlocal variables,
  # as are `arg_1` and `arg_2`.
  value = 22
  my_dict = {'chocolate': 'yummy'}

  def child():
    print(2 * value)
    print(my_dict['chocolate'])
    print(arg_1 + arg_2)

  return child
Python 函数编写

闭包(closure):附着在被返回函数上的非局部变量。

def parent(arg_1, arg_2):
  value = 22
  my_dict = {'chocolate': 'yummy'}

  def child():
    print(2 * value)
    print(my_dict['chocolate'])
    print(arg_1 + arg_2)

  return child

new_function = parent(3, 4)

print([cell.cell_contents for cell in new_function.__closure__])
[3, 4, 22, {'chocolate': 'yummy'}]
Python 函数编写

为何重要?

装饰器利用:

  • 函数是对象
  • 嵌套函数
  • 非局部作用域
  • 闭包
Python 函数编写

Passons à la pratique !

Python 函数编写

Preparing Video For Download...