2009-07-04 39 views
4

我的目标是解析一个类并返回描述类中包含的方法和相关参数的数据结构(对象,字典等)。奖励积分的类型和回报......如何以编程方式报告类的API?

要求:必须是Python的

例如,下面的类:

class Foo: 
    def bar(hello=None): 
     return hello 

    def baz(world=None): 
     return baz 

将解析返回

result = {class:"Foo", 
      methods: [{name: "bar", params:["hello"]}, 
        {name: "baz", params:["world"]}]} 

所以这是只是我在想什么的一个例子......我对数据结构非常灵活。

有关如何实现此目的的任何想法/示例?

+0

看起来问题http://stackoverflow.com/questions/990016/how-to-find-out-the-arity-of-a-method-in-python,它包含你将需要的,也解释了你不能做 – 2009-07-04 04:21:20

回答

8

你可能想看看Python的inspect模块。这将让你最那里的方式:

>>> class Foo: 
...  def bar(hello=None): 
...   return hello 
...  def baz(world=None): 
...   return baz 
... 
>>> import inspect 
>>> members = inspect.getmembers(Foo) 
>>> print members 
[('__doc__', None), ('__module__', '__main__'), ('bar', <unbound method Foo.bar> 
), ('baz', <unbound method Foo.baz>)] 
>>> inspect.getargspec(members[2][1]) 
(['hello'], None, None, (None,)) 
>>> inspect.getargspec(members[3][1]) 
(['world'], None, None, (None,)) 

这不是你想要的语法,但是这部分应该是相当简单的,你阅读文档。

+1

`inspect`看起来就像你要找的东西。对于更低科技的解决方案,你可以看一看`Foo .__ dict__`,其中包含Foo类的所有成员。 – 2009-07-04 03:16:41

相关问题