Python内省:如何获取类方法的varnames?

时间:2010-03-29 09:28:34

标签: 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

一旦周围环境变得更加稳定,我会考虑更好的解决方案。

2 个答案:

答案 0 :(得分:10)

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

答案 1 :(得分:5)

嗯,作为你所做事的直接延伸:

for varname in a.__class__.__dict__['A1'].__code__.co_varnames:
    print varname

打印:

self
test1

P.S。:说实话,我觉得这可以更优雅地完成......

例如,您可以将a.__class__替换为A,但您知道;-)