Decorators met argumenten

Functies schrijven in 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
Functies schrijven in Python

run_n_times()

def run_n_times(func):
  def wrapper(*args, **kwargs):
    # Hoe geven we "n" door aan deze functie?
    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!')
Functies schrijven in Python

Een decoratorfabriek

def run_n_times(n):
  """Definieer en geef een decorator terug"""

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)
Functies schrijven in Python
def run_n_times(n):
  """Definieer en geef een decorator terug"""
  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)
Functies schrijven in Python

run_n_times() gebruiken

@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!
Functies schrijven in Python

Laten we oefenen!

Functies schrijven in Python

Preparing Video For Download...