Dekorátory

Writing Functions in Python

Shayne Miel

Software Architect @ Duo Security

Funkce

funkce

Writing Functions in Python

Dekorátory

funkce s dekorátorem

Writing Functions in Python

Úprava vstupů

úprava vstupů

Writing Functions in Python

Úprava výstupů

úprava výstupů

Writing Functions in Python

Úprava funkce

úprava funkce

Writing Functions in Python

Jak vypadá dekorátor?

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

multiply(1, 5)
20
Writing Functions in Python

Dekorátor 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
Writing Functions in Python

Dekorátor double_args

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

def double_args(func):
# Definujeme novou funkci, kterou můžeme upravit def wrapper(a, b):
# Zatím jen zavolá neupravenu funkci return func(a, b)
# Vrátí novou funkci return wrapper
new_multiply = double_args(multiply)
new_multiply(1, 5)
5
Writing Functions in Python

Dekorátor double_args

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

def double_args(func): def wrapper(a, b):
# Zavolá předanou funkci, ale zdvojí každý argument return func(a * 2, b * 2)
return wrapper
new_multiply = double_args(multiply)
new_multiply(1, 5)
20
Writing Functions in Python

Dekorátor 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>
Writing Functions in Python

Syntaxe dekorátoru

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
Writing Functions in Python

Lass uns üben!

Writing Functions in Python

Preparing Video For Download...