简体   繁体   English

在python装饰器处获取传递参数

[英]Get passing argument at python decorator

def deco_test(func):
    def inner_function(*args, **kwargs):
        return func(*args, **kwargs)
    return inner_function

@deco_test
def a(a='asdf', b='asdf'):
    pass

if __name__ == '__main__':
    a(456, 789)
    a(123, b='qwer/123/a.txt')
    a(a='098', b='789456')    

I want to get argument like this: 我想得到这样的论点:

  1. {'a': 456, 'b': 789} {'a':456,'b':789}
  2. {'a': 123, 'b': 'qwer/123/a.txt'} {'a':123,'b':'qwer / 123 / a.txt'}
  3. {'a': '098', 'b':'789456'} {'a':'098','b':'789456'}

in deco_test(func) deco_test(func)

You will not get access to the parameter you provide to a inside deco_test . 你将不能访问你提供的参数a内部deco_test The decoration is done when the function is declared, before you call the function and at that point in time you have no information about those arguments. 修饰是在声明函数时完成的,在调用函数之前,那时您没有关于这些参数的信息。

Inside the inner_function you get arguments as provided in the decorated function call a(456, 789) will give you args=(456, 789) . inner_function内部,您得到修饰函数调用a(456, 789) inner_function中提供的参数a(456, 789)将为您args=(456, 789) If you want to format them according to the arguments that a can take, I think you have to inspect on the function a . 如果要根据a可以接受的参数来格式化它们,我认为您必须检查函数a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM