Skip to main content
 首页 » 编程设计

python之提取 python 方法参数的数量和名称

2025年05月04日9zlslch

如何返回不同模块中函数的参数

#Module: functionss.py 
def simple(a, b, c): 
    print "does something" 
 
 
#Module: extract.py 
#load the called module and function 
def get_args(module_name, function_name): 
    modFile, modPath, modDesc = imp.find_module(module_name) 
    mod = imp.load_module(module_name,modFile,modPath,modDesc) 
    attr = getattr(mod, function_name) 
 
#this is the part I don't get - how do I read the arguments 
    return = attr.get_the_args() 
 
 if __name__ == "__main__": 
     print get_args("functions.py", "simple") 
 
 #this would ideally print [a, b, c] 

请您参考如下方法:

使用inspect.getargspec对于“繁重的工作”(内省(introspection)一个函数)。

使用 __import__ 导入模块(给定其模块名称 -- "functions.py" 是指定模块的糟糕方式姓名;-).

使用 getattr(moduleobject, functionname) 获取给定模块对象和函数名称的函数对象。