在裝飾函式時保留 docstring
你的朋友遇到一個問題。他們寫了幾個不錯的 decorator,並把它們加到自己正在開發的開源函式庫的函式上。不過在跑測試時發現,被裝飾過的函式居然都不見了 docstring。請示範如何在撰寫 decorator 時保留 docstring 與其他中繼資料(metadata)。
本練習屬於課程
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)