装饰器中的Python Access函数变量

时间:2017-10-26 13:26:59

标签: python-2.7 arguments decorator

我想谈谈以下内容:

假设我有以下功能:

def query(self, url, method = 'GET',payload=None):
    if method == "GET":
        result = requests.get(self.api_base_url+url, auth=self.__auth_token, verify=False)
        print (result)
    elif method == "POST":
        result = requests.post(self.api_base_url+url, auth=self.__auth_token, data=payload, verify=False)
        print(result)
    elif method == "PUT":
        result = requests.put(self.api_base_url+url, auth=self.__auth_token, data=payload, verify=False)
        print(result)

我想测量休息电话所需的时间。所以我开始构建一个装饰器来测量休息时间。

def timing(f):
        def wrap(*args):
            time1 = time.time()
            ret = f(*args)
            time2 = time.time()
            time_took = time2-time1
            print (time_took)
        return wrap

现在我要打印有效载荷。但仅适用于PUT和POST请求,而不适用于GET请求。所以我需要在装饰器中检查参数method,但我无法在装饰器中访问此参数。特别是我想做这样的事情:

def timing(f):
        def wrap(*args):
            time1 = time.time()
            ret = f(*args)
            time2 = time.time()
            time_took = time2-time1
            if args[0].method == 'PUT' and args[0].method == 'POST'
                print (time_took + args.[0].payload)
            else:
                print (time_took)
        return wrap

问题:

如何在装饰器中访问函数的参数?

由于

1 个答案:

答案 0 :(得分:0)

就像你尝试过的那样,但没有.methodargs是一个参数元组。

def deco(f):
    def inner(*args):
        print(args[0])
        return f(*args)
    return inner


@deco
def foo(a):
    pass

foo('a')
# a


如果你不想跟踪这些论点'索引可以使用kwargs

def deco(f):
    def inner(*args, **kwargs):
        print(kwargs['a'])
        print(kwargs['b'])
        return f(*args, **kwargs)
    return inner


@deco
def foo(a, b):
    pass

foo(a=1, b=2)
# 1
# 2