【发布时间】:2016-04-20 13:43:30
【问题描述】:
为什么在下面的装饰器示例中wrapper() 函数需要*args 和**kwargs?
def currency(f):
def wrapper(*args, **kwargs):
return '$' + str(f(*args, **kwargs))
return wrapper
class Product(db.Model):
name = db.StringColumn
price = db.FloatColumn
@currency
def price_with_tax(self, tax_rate_percentage):
"""Return the price with *tax_rate_percentage* applied.
*tax_rate_percentage* is the tax rate expressed as a float, like "7.0"
for a 7% tax rate."""
return price * (1 + (tax_rate_percentage * .01))
传递给price_with_tax(self, tax_rate_percentage) 的参数不是已经在def currency(f) 函数的范围内可用,因此对wrapper() 函数可用吗?
为什么我们不能直接将f() 传递给wrapper()?
我只是想了解为什么 wrapper() 有 *args 和 **kwargs 以及两者如何将参数传递给 price_with_tax(self, tax_rate_percentage)
【问题讨论】:
标签: python function python-2.7 decorator python-decorators