การกำหนด decorator
เพื่อนของคุณกำลังสร้าง decorator ที่พิมพ์ข้อความ "before" ก่อนที่ฟังก์ชันที่ถูก decorate จะถูกเรียก และพิมพ์ข้อความ "after" หลังจากที่ฟังก์ชันทำงานเสร็จแล้ว แต่ติดปัญหาเรื่องการ wrap ฟังก์ชัน ช่วยเพื่อนด้วยการเติมโค้ดใน decorator print_before_and_after() ให้สมบูรณ์
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การเขียนฟังก์ชันใน Python
คำแนะนำการฝึกหัด
- เรียกใช้ฟังก์ชันที่ถูก decorate และส่งอาร์กิวเมนต์แบบ positional
*argsเข้าไป - คืนค่าฟังก์ชันที่ถูก decorate ใหม่
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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)