0

我想列出我的自记录 REST API 方法的参数。我发现我可以使用以下方法获取方法的参数:

method.__code__.co_varnames[:method.__code__.co_argcount]

但是,当方法被修饰时,这不起作用。

class Rator:

    def __init__(self):
        pass

    def __call__(self, func):
        def wrapper(instance, **kwargs):
            func(instance, **kwargs)
        return wrapper


class Klass:

    def method(self, var_one=None, var_two=None):
        pass

    @Rator()
    def decorated_method(self, var_one=None, var_two=None):
        pass


if __name__ == '__main__':
    klass = Klass()
    print("method args is " + str(klass.method.__code__.co_varnames))
    print("decorated method args is " + str(klass.decorated_method.__code__.co_varnames))

输出

method args is ('self', 'var_one', 'var_two')
decorated method args is ('instance',)

不需要更改装饰器的解决方案是首选。

我知道这个问题是How to retrieve method arguments of a decorated python method的副本,但它早就死了。

4

1 回答 1

4

你需要用functools.wraps包装你的装饰器,然后你可以通过inspect.signature()检查方法:

import inspect
from functools import wraps


class Rator:
    def __init__(self):
        pass

    def __call__(self, func, **kwargs):
        @wraps(func)
        def wrapper(instance):
            func(instance, **kwargs)
        return wrapper


class Klass:
    def method(self, var_one=None, var_two=None):
        pass

    @Rator()
    def decorated_method(self, argument1, var_one=None, var_two=None):
        pass


if __name__ == '__main__':
    klass = Klass()
    print("method args is ", inspect.signature(klass.method))
    print("decorated method args is ", inspect.signature(klass.decorated_method))

印刷:

method args is  (var_one=None, var_two=None)
decorated method args is  (argument1, var_one=None, var_two=None)
于 2019-01-28T10:42:05.333 回答