【问题标题】:Python: Passing the default values of function' arguments to *args or **kwargsPython:将函数参数的默认值传递给 *args 或 **kwargs
【发布时间】:2015-01-28 09:43:38
【问题描述】:

考虑例子:

def decorator(func):
    def wrapper(*args, **kwargs):
        print(args, kwargs)
        func(*args, **kwargs)
    return wrapper

@decorator
def foo(x, y, z=0):
    pass

foo(5, 5)

输出:

(5, 5) {}

为什么不(5, 5) {'z': 0}?如何仅使用装饰器(用于函数)或元类(用于类方法,例如__init__)将函数foo的所有默认值传递给*args或**kwargs?

【问题讨论】:

  • 另请注意,如果您使用foo(5, 5, 42),wrapper 会收到(5, 5, 42),但如果您使用foo(5, 5, z=42),它将收到(5, 5), {'z': 42}

标签: python python-3.x decorator default-value metaclass


【解决方案1】:

包装器只是一个普通函数。它无法“访问”被包装函数的内部。

您必须使用自省来获得它们。查看相关问题:

How to find out the default values of a particular function's argument in another function in Python?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-22
    • 2013-07-26
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多