Python内省:如何获取类方法的varnames? [英] Python Introspection: How to get varnames of class methods?
问题描述
我想获取类的方法的关键字参数的名称。我想我知道如何获得方法的名称和如何获得一个特定方法的变量名称,但我不知道如何结合这些:
I want to get the names of the keyword arguments of the methods of a class. I think I understood how to get the names of the methods and how to get the variable names of a specific method, but I don't get how to combine these:
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发布这些数据。
I will have to expose the names of the methods and their arguments to an external API. I have written a twisted app to link to the mentioned api and this twisted app will have to publish this data via the api.
所以,我想我会使用像:
So, I think I will use something like:
for methodname in A.__dict__.keys():
if not methodname.startswith('__'):
print methodname
for varname in A.__dict__[methodname].__code__.co_varnames:
print varname
$
推荐答案
一旦环境变得更稳定,我会考虑更好的解决方案。好吧,作为你所做的直接扩展:
Well, as a direct extension of what you did:
for varname in a.__class__.__dict__['A1'].__code__.co_varnames:
print varname
列印:
self
test1
em> PS:说实话,我有一种感觉,这可以做得更优雅...
P.S.: to be honest, I have a feeling this can be done more elegantly...
例如,你可以替换 a .__ class __
与 A
,但你知道;-)
For example, you can replace a.__class__
with A
, but you knew that ;-)
这篇关于Python内省:如何获取类方法的varnames?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!