【发布时间】:2019-04-11 14:19:49
【问题描述】:
我编写了以下程序来为price_report 和sales_report 两个函数提供包装器(装饰器)。我刚刚将包装器分配给这些函数(下面代码中的最后两行),而没有显式调用price_report() 或sales_report()。但是代码会产生下面进一步显示的输出。怎么会?
事实上,如果我显式调用price_report(),我会收到错误消息TypeError: 'NoneType' object is not callable。
# wrapper.py
def wrapper(report):
def head_and_foot(report):
print(report.__name__)
report()
print("End of", report.__name__, "\n\n")
return head_and_foot(report)
def price_report():
cars = ['Celerio', 'i10', 'Amaze', 'Figo']
price = [500_000, 350_000, 800_000, 550_000]
for x, y in zip(cars, price):
print(f'{x:8s}', f'{y:8,d}')
def sales_report():
cars = ['Celerio', 'i10', 'Amaze', 'Figo']
units = [5000, 3000, 1000, 800]
for x, y in zip(cars, units):
print(f'{x:8s}', f'{y:8,d}')
sales_report = wrapper(sales_report)
price_report = wrapper(price_report)
上述程序的输出(无论是在 Jupyter notebook 中运行还是从命令行以python wrapper.py 运行):
sales_report
Celerio 5,000
i10 3,000
Amaze 1,000
Figo 800
End of sales_report
price_report
Celerio 500,000
i10 350,000
Amaze 800,000
Figo 550,000
End of price_report
【问题讨论】:
标签: python python-3.x python-decorators