Closures

การเขียนฟังก์ชันใน Python

Shayne Miel

Software Architect @ Duo Security

การผูกตัวแปร nonlocal เข้ากับฟังก์ชันซ้อน

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

func = foo()

func()
5

Closures!

type(func.__closure__)
<class 'tuple'>
len(func.__closure__)
1
func.__closure__[0].cell_contents
5
การเขียนฟังก์ชันใน Python

Closures และการลบตัวแปร

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

Closures และการเขียนทับตัวแปร

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

นิยาม - ฟังก์ชันซ้อน

ฟังก์ชันซ้อน (Nested function): ฟังก์ชันที่นิยามอยู่ภายในฟังก์ชันอื่น

# outer function
def parent():
  # nested function
  def child():
    pass
  return child
การเขียนฟังก์ชันใน Python

นิยาม - ตัวแปร nonlocal

ตัวแปร 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: ตัวแปร nonlocal ที่ผูกติดกับฟังก์ชันที่ถูก return กลับมา

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

ทำไมสิ่งเหล่านี้จึงสำคัญ?

Decorators ใช้:

  • ฟังก์ชันในฐานะออบเจกต์
  • ฟังก์ชันซ้อน
  • Nonlocal scope
  • Closures
การเขียนฟังก์ชันใน Python

มาฝึกกันเถอะ!

การเขียนฟังก์ชันใน Python

Preparing Video For Download...