首页 > 解决方案 > 如果我们只有字符串类型的方法名称,有没有办法获取方法需要的参数数量?

问题描述

首先,我使用的是 python 2.7.13,所以我的选择非常有限。我试过了:

@some_decorator
def xyz(self,a,b,c):
    pass
function_name = " xyz"    
inspect.getargspec(getattr(self,function_name))

它给出了:

ArgSpec(args=[], varargs='args', keywords='kwargs', defaults=None)

由于装饰器,它给出了 0 个参数。如果我尝试其他方法,它会给出正确的参数列表。

标签: pythonpython-2.7arguments

解决方案


其中一种解决方案可以使用 ast 模块:

import ast    
def GetAllMethodsArgs(self):
    with open(os.path.abspath(__file__)) as file:
        node = ast.parse(file.read())

    classDefinitions = [n for n in node.body if isinstance(n, ast.ClassDef)]
    for classDef in classDefinitions:
        functions = [n for n in classDef.body if isinstance(n, ast.FunctionDef)]

    for function in functions:
        self.methodArgsdict[function.name] = len(function.args.args)

在定义 methodArgsdict = {} 之后,在类的 init 中调用它。此函数将使用函数名称作为键和参数作为其值填充字典。


推荐阅读