การรักษา docstring เมื่อใช้ decorator กับฟังก์ชัน
เพื่อนของคุณมาขอความช่วยเหลือ พวกเขาเขียน decorator ที่ดูดีและนำไปใช้กับฟังก์ชันในไลบรารี open-source ที่กำลังพัฒนาอยู่ แต่เมื่อรันการทดสอบก็พบว่า docstring ของฟังก์ชันที่ถูก decorate ไว้หายไปหมดอย่างไม่ทราบสาเหตุ ช่วยแสดงให้เพื่อนเห็นว่าต้องทำอย่างไรเพื่อรักษา docstring และ metadata อื่น ๆ ไว้เมื่อเขียน decorator
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การเขียนฟังก์ชันใน Python
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
def add_hello(func):
def wrapper(*args, **kwargs):
print('Hello')
return func(*args, **kwargs)
return wrapper
# Decorate print_sum() with the add_hello() decorator
____
def print_sum(a, b):
"""Adds two numbers and prints the sum"""
print(a + b)
print_sum(10, 20)
# Define the docstring
print_sum_docstring = print_sum.____
print(print_sum_docstring)