【发布时间】:2011-02-01 23:21:31
【问题描述】:
我想获取类方法的关键字参数的名称。我想我了解如何获取方法的名称以及如何获取特定方法的变量名称,但我不知道如何组合这些:
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
一旦环境稳定了,我会考虑更好的解决方案。
【问题讨论】:
-
python 2.5 不喜欢 A.__dict__[methodname].__code__.co_varnames -- 'function' 对象没有属性 'code' 使用 inspect 可能更稳定python 版本。
标签: python class introspection