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

dac*_*cle 5 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
Run Code Online (Sandbox Code Playgroud)

我将不得不将方法的名称及其参数公开给外部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
Run Code Online (Sandbox Code Playgroud)

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

Edd*_*onk 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
Run Code Online (Sandbox Code Playgroud)


Eli*_*sky 5

好吧,作为你所做的直接延伸:

for varname in a.__class__.__dict__['A1'].__code__.co_varnames:
    print varname
Run Code Online (Sandbox Code Playgroud)

打印:

self
test1
Run Code Online (Sandbox Code Playgroud)

PS:说实话,我觉得这可以做得更优雅......

例如,您可以替换a.__class__使用A,但你知道;-)

  • @ironfroggy为什么你认为这是一件愚蠢的事情? (2认同)