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