可帶引數的裝飾器

Python 函式寫作

Shayne Miel

Software Architect @ Duo Security

def run_three_times(func):
  def wrapper(*args, **kwargs):
    for i in range(3):
      func(*args, **kwargs)
  return wrapper

@run_three_times def print_sum(a, b): print(a + b)
print_sum(3, 5)
8
8
8
Python 函式寫作

run_n_times()

def run_n_times(func):
  def wrapper(*args, **kwargs):
    # 我們要如何把「n」傳進這個函式?
    for i in range(???):
      func(*args, **kwargs)
  return wrapper

@run_n_times(3) def print_sum(a, b): print(a + b)
@run_n_times(5) def print_hello(): print('Hello!')
Python 函式寫作

裝飾器工廠

def run_n_times(n):
  """定義並回傳一個裝飾器"""

def decorator(func):
def wrapper(*args, **kwargs):
for i in range(n): func(*args, **kwargs)
return wrapper
return decorator
@run_n_times(3) def print_sum(a, b): print(a + b)
Python 函式寫作
def run_n_times(n):
  """定義並回傳一個裝飾器"""
  def decorator(func):
    def wrapper(*args, **kwargs):
      for i in range(n):
        func(*args, **kwargs)
    return wrapper
  return decorator

run_three_times = run_n_times(3)
@run_three_times def print_sum(a, b): print(a + b)
@run_n_times(3) def print_sum(a, b): print(a + b)
Python 函式寫作

使用 run_n_times()

@run_n_times(3)
def print_sum(a, b):
  print(a + b)

print_sum(3, 5)
8
8
8
@run_n_times(5)
def print_hello():
  print('Hello!')

print_hello()
Hello!
Hello!
Hello!
Hello!
Hello!
Python 函式寫作

一起來練習吧!

Python 函式寫作

Preparing Video For Download...