Python 自省(introspection) : How to get varnames of class methods?

标签 python class introspection

我想获取类方法的关键字参数的名称。我想我了解如何获取方法的名称以及如何获取特定方法的变量名称,但我不知道如何组合这些:

class A(object):
    def A1(self, test1=None):
        self.test1 = test1
    def A2(self, test2=None):
        self.test2 = test2
    def A3(self):
        pass
    def A4(self, test4=None, test5=None):
        self.test4 = test4
        self.test5 = test5

a = A()

# to get the names of the methods:

for methodname in a.__class__.__dict__.keys():
    print methodname

# to get the variable names of a specific method:

for varname in a.A1.__func__.__code__.co_varnames:
    print varname

# I want to have something like this:
for function in class:
    print function.name
    for varname in function:
        print varname

# desired output:
A1
self
test1
A2
self
test2
A3
self
A4
self
test4
test5

我将不得不向外部 API 公开方法的名称及其参数。我已经编写了一个扭曲的应用程序来链接到提到的 api,这个扭曲的应用程序必须通过 api 发布这些数据。

所以,我想我会使用类似的东西:

for methodname in A.__dict__.keys():
if not methodname.startswith('__'):
    print methodname
    for varname in A.__dict__[methodname].__code__.co_varnames:
        print varname

一旦环境稳定下来,我就会考虑更好的解决方案。

最佳答案

import inspect

for name, method in inspect.getmembers(a, inspect.ismethod):
    print name
    (args, varargs, varkw, defaults) = inspect.getargspec(method)
    for arg in args:
        print arg

关于Python 自省(introspection) : How to get varnames of class methods?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2536879/

相关文章:

python - 如何从包含年份和月份的单个日期列中为每年创建一个列?

python - 如何在 Python 中检查字符串中是否包含数值?

Python Django 如何在views.py 中获取登录用户的值?

python - django - 具有模型类如何获取所有字段的列表、它们的类型和传递的参数?

python - 使用格式和变量将字符串居中

python - 如何将模型导入 django 项目中的 python 文件?

C++ 创建类对象和循环包含的问题

python - 使用 super() 访问第二个基类的方法

python - 改变 python 记录器堆栈级别

java - 如何让 Spring 接受流畅(非 void)的 setter ?