MulaiMulai sekarang secara gratis

Defining a decorator

Your buddy has been working on a decorator that prints a "before" message before the decorated function is called and prints an "after" message after the decorated function is called. They are having trouble remembering how wrapping the decorated function is supposed to work. Help them out by finishing their print_before_and_after() decorator.

Latihan ini adalah bagian dari kursus

Writing Functions in Python

Lihat Kursus

Petunjuk latihan

  • Call the function being decorated and pass it the positional arguments *args.
  • Return the new decorated function.

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

def print_before_and_after(func):
  def wrapper(*args):
    print('Before {}'.format(func.__name__))
    # Call the function being decorated with *args
    ____(*args)
    print('After {}'.format(func.__name__))
  # Return the nested function
  return ____

@print_before_and_after
def multiply(a, b):
  print(a * b)

multiply(5, 10)
Edit dan Jalankan Kode