Python 了解decorator函数中的作用域和*args和**kwargs

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

为什么在下面的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

    @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
这样的修饰器通常使用变量参数来处理所有情况