将默认参数传递给python中的装饰器 [英] Passing default arguments to a decorator in python

查看:195
本文介绍了将默认参数传递给python中的装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试寻找一种方法来将函数的默认参数传递给装饰器.我不得不说我对装饰器行业还很陌生,所以也许我只是不太了解它,但是我还没有找到任何答案.

I am trying to find a way to pass my functions default arguments to the decorator. I have to say I am fairly new to the decorator business, so maybe I just don't understand it properly, but I have not found any answers yet.

因此,这里是我在python functools.wraps手册页上修改的示例.

So here my modified example from the python functools.wraps manual page.

from functools import wraps
def my_decorator(f):
    @wraps(f)
    def wrapper(*args, **kwds):
            print 'Calling decorated function'
            print 'args:', args 
            print 'kwargs:', kwds   
            return f(*args, **kwds)
    return wrapper

@my_decorator
def example(i, j=0):
    """Docstring"""
    print 'Called example function'

example(i=1)

我也希望通过j=0.这样输出应该是:

I want the j=0 to be passed, too. So that the output should be:

Calling decorated function
args: ()
kwargs: {'i': 1, 'j': 0}
Called example function

推荐答案

您可以使用__defaults__特殊属性来获取默认参数值.

You can get default argument values by using __defaults__ special attribute.

def my_decorator(f):
@wraps(f)
def wrapper(*args, **kwds):
    print('def args values', f.__defaults__)
    return f(*args, **kwds)
return wrapper

参考:在__defaults__rel ="nofollow noreferrer"> https ://docs.python.org/3/reference/datamodel.html#the-standard-type-hierarchy

Reference: look for __defaults__ in https://docs.python.org/3/reference/datamodel.html#the-standard-type-hierarchy

包含具有默认值的参数的默认参数值的元组;如果没有参数具有默认值,则为None

A tuple containing default argument values for those arguments that have defaults, or None if no arguments have a default value

这篇关于将默认参数传递给python中的装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆