Decorators

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

Shayne Miel

Software Architect @ Duo Security

ฟังก์ชัน

ฟังก์ชัน

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

Decorators

ฟังก์ชันพร้อม decorator

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

ปรับแต่ง input

ปรับแต่ง input

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

ปรับแต่ง output

ปรับแต่ง output

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

ปรับแต่งฟังก์ชัน

ปรับแต่งฟังก์ชัน

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

Decorator มีหน้าตาอย่างไร?

@double_args
def multiply(a, b):
  return a * b

multiply(1, 5)
20
การเขียนฟังก์ชันใน Python

Decorator double_args

def multiply(a, b):
  return a * b

def double_args(func): return func
new_multiply = double_args(multiply)
new_multiply(1, 5)
5
multiply(1, 5)
5
การเขียนฟังก์ชันใน Python

Decorator double_args

def multiply(a, b):
  return a * b

def double_args(func):
# Define a new function that we can modify def wrapper(a, b):
# For now, just call the unmodified function return func(a, b)
# Return the new function return wrapper
new_multiply = double_args(multiply)
new_multiply(1, 5)
5
การเขียนฟังก์ชันใน Python

Decorator double_args

def multiply(a, b):
  return a * b

def double_args(func): def wrapper(a, b):
# Call the passed in function, but double each argument return func(a * 2, b * 2)
return wrapper
new_multiply = double_args(multiply)
new_multiply(1, 5)
20
การเขียนฟังก์ชันใน Python

Decorator double_args

def multiply(a, b):
  return a * b

def double_args(func): def wrapper(a, b): return func(a * 2, b * 2) return wrapper
multiply = double_args(multiply)
multiply(1, 5)
20
multiply.__closure__[0].cell_contents
<function multiply at 0x7f0060c9e620>
การเขียนฟังก์ชันใน Python

ไวยากรณ์ของ decorator

def double_args(func):
  def wrapper(a, b):
    return func(a * 2, b * 2)
  return wrapper

def multiply(a, b): return a * b multiply = double_args(multiply) multiply(1, 5)
20
def double_args(func):
  def wrapper(a, b):
    return func(a * 2, b * 2)
  return wrapper

@double_args def multiply(a, b): return a * b multiply(1, 5)
20
การเขียนฟังก์ชันใน Python

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

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

Preparing Video For Download...