Python 了解decorator函数中的作用域和*args和**kwargs
为什么在下面的decorator示例中,Python 了解decorator函数中的作用域和*args和**kwargs,python,function,python-2.7,decorator,python-decorators,Python,Function,Python 2.7,Decorator,Python Decorators,为什么在下面的decorator示例中,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
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\u with\u tax(self,tax\u rate\u percentage)
的参数是否已在def currency(f)
函数的范围内可用,因此可用于wrapper()
函数
为什么我们不能直接将f()
传递到wrapper()
我只是想了解为什么
wrapper()
有*args
和**kwargs
,以及它们是如何通过税(self,tax\u rate\u percentage)将参数传递给price\u的一个包装器将一个函数作为参数并返回另一个函数。为了使返回的函数尽可能有用(即,应用于任何函数或方法),它必须接受任意数量的参数
想想装饰师是干什么的。这:
@currency
def price_with_tax(self, tax_rate_percentage):
return price * (1 + (tax_rate_percentage * .01))
基本上只是这方面的简写:
def price_with_tax(self, tax_rate_percentage):
return price * (1 + (tax_rate_percentage * .01))
price_with_tax = currency(price_with_tax)
也就是说,price\u with\u tax
最终是currency
的返回值,因此它还应该是一个至少包含两个参数的函数(self
和tax\u rate\u percentage
)
但是,@currency
可以用来修饰许多其他函数,这些函数可能使用不同数量的参数和不同的关键字参数,因此像currency
这样的修饰器通常使用变量参数来处理所有情况