Counter
กำลังพัฒนาเว็บแอปใหม่ และอยากรู้ว่าแต่ละฟังก์ชันในแอปถูกเรียกใช้กี่ครั้ง จึงตัดสินใจเขียน decorator ที่เพิ่มตัวนับ (counter) ให้กับแต่ละฟังก์ชันที่ต้องการติดตาม ข้อมูลนี้จะเป็นประโยชน์ในอนาคต เพื่อดูว่ามีส่วนใดของโค้ดที่ไม่ได้ถูกใช้งานแล้วและสามารถตัดออกได้
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การเขียนฟังก์ชันใน Python
คำแนะนำการฝึกหัด
- เรียกใช้ฟังก์ชันที่ถูก decorate และ return ผลลัพธ์
- Return ฟังก์ชันที่ถูก decorate แล้วออกไป
- Decorate
foo()ด้วยcounter()decorator
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
def counter(func):
def wrapper(*args, **kwargs):
wrapper.count += 1
# Call the function being decorated and return the result
return ____
# Set count to 0 to initialize call count for each new decorated function
wrapper.count = 0
# Return the new decorated function
____
# Decorate foo() with the counter() decorator
____
def foo():
print('calling foo()')
foo()
foo()
print('foo() was called {} times.'.format(foo.count))