python - 如果我们只有字符串类型的方法名称,有没有办法获取方法需要的参数数量?
问题描述
首先,我使用的是 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 个参数。如果我尝试其他方法,它会给出正确的参数列表。
解决方案
其中一种解决方案可以使用 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 中调用它。此函数将使用函数名称作为键和参数作为其值填充字典。
推荐阅读
- com - 注册 DirectshowFilter 将 InprocServer32 注册表项链接到 regsvr32.exe 而不是主机 DLL,我哪里出错了?
- html - 图像大小改进和 CSS 文件
- javascript - KnockoutJS - 可观察对象的可观察数组,包含来自 SQL 服务器的数据
- c# - C# .NET 到 Docker 上的 Apache Ignite
- excel - 设置 HTML_Content = CreateObject("htmlfile") 不起作用
- list - 为什么有时你必须创建一个新列表而有时你不需要在 Unity 中?
- azure - 从 Visual Studio,无法发布到 Azure 应用服务
- python - 在没有 iterrows 的情况下更新 Pandas 行
- macos - Hadoop 3.1.1 Mac OS Namenode 问题
- php - WordPress AJAX (php/MySQL) - 如何将代码/定义的可重用部分移动到外部文件或函数?