2011-10-02 33 views
8

我試圖使用inspect模塊,但它似乎我不能使用它內置的(原生?)類,否則我誤解。如何獲取內建Python類構造函數的參數列表?

我使用Python 2.7,並使用Python 3.2試過。

這是工作:

>>> import inspect 
>>> class C: 
...  def __init__(self,a,b=4): 
...   self.sum = a + b 
... 
>>> inspect.getargspec(C.__init__) 
ArgSpec(args=['self','a', 'b'], varargs=None, keywords=None, defaults=(4,)) 

這不是工作:

>>> import inspect 
>>> import ast 
>>> inspect.getargspec(ast.If.__init__) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 813, in getargspec 
    raise TypeError('{!r} is not a Python function'.format(func)) 
TypeError: <slot wrapper '__init__' of '_ast.AST' objects> is not a Python function 

我想知道是否有另一種技術來自動獲取這些參數?在我的情況下,我想要解析Python語法的ASDL文件,該文件解釋瞭如何使用我在PyPy Project的源代碼中看到的一些代碼來初始化AST節點,但是我想知道是否在那裏另一種方式)

回答

5

注意,該代碼的工作只是罰款PyPy(那裏沒有真正的兩個函數類型的區分)。

(pypy)[email protected]:~$ python 
class C(Python 2.7.1 (f1e873c5533d, Sep 19 2011, 02:01:57) 
[PyPy 1.6.0-dev1 with GCC 4.4.3] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
Welcome to rlcompleter2 0.96 
for nice experiences hit <tab> multiple times 
And now for something completely different: ``PyPy needs a Just-in-Time JIT'' 
>>>> class C: 
.... def __init__(self, a, b=4): 
.... pass 
.... 
>>>> import inspect 
>>>> inspect.getargspec(C.__init__) 
ArgSpec(args=['self', 'a', 'b'], varargs=None, keywords=None, defaults=(4,)) 
>>>> 
相關問題