定義一個 decorator
你的同事正在開發一個 decorator:在被裝飾的函式呼叫前先列印一則「before」訊息,函式結束後再列印一則「after」訊息。他們一時想不起來該如何包裹(wrap)被裝飾的函式。請幫他們完成 print_before_and_after() 這個 decorator。
本練習屬於課程
Python 函式寫作
練習說明
- 呼叫被裝飾的函式,並將位置引數
*args傳入。 - 回傳新的被裝飾函式。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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)