【问题标题】:Why do we need `*args` in decorator? [duplicate]为什么我们在装饰器中需要`*args`? [复制]
【发布时间】:2018-02-23 03:02:57
【问题描述】:
def pass_thru(func_to_decorate):
    def new_func(*args, **kwargs):  #1
        print("Function has been decorated.  Congratulations.")
        # Do whatever else you want here
        return func_to_decorate(*args, **kwargs)  #2
    return new_func


def print_args(*args):
    for arg in args:
        print(arg)


a = pass_thru(print_args)
a(1,2,3)

>> Function has been decorated.  Congratulations.
1
2
3

我知道*args 在#1 中使用,因为它是一个函数声明。但是为什么*args即使不是函数声明也要在#2中写呢?

【问题讨论】:

  • 您将位置参数捆绑到 args 元组中,然后在调用包装函数时将它们解绑成单独的参数。

标签: python decorator args


【解决方案1】:

在函数声明中使用时,*args 将位置参数转换为元组:

def foo(a, *args):
    pass
foo(1, 2, 3)    #  a = 1, args = (2, 3)

在函数调用中使用时,*args 将元组扩展为位置参数:

def bar(a, b, c):
    pass
args = (2, 3)
foo(1, *args)   # a = 1, b = 2, c = 3

这是两个相反的过程,因此将它们结合起来可以将任意数量的参数传递给修饰函数。

@pass_thru
def foo(a, b):
    pass
@pass_thru
def bar(a, b, c):
    pass

foo(1, 2)     # -> args = (1, 2) -> a = 1, b = 2
bar(1, 2, 3)  # -> args = (1, 2, 3) -> a = 1, b = 2, c = 3

【讨论】:

    猜你喜欢
    • 2011-01-02
    • 2018-04-17
    • 2010-09-21
    • 2018-01-02
    • 2019-01-18
    • 2012-03-22
    • 2011-03-29
    • 1970-01-01
    相关资源
    最近更新 更多