2011-10-02 10 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の文法を解析する代わりに、PyPy Projectのソースで見たコードを使ってASTノードを初期化する方法を説明するASDLファイルを考えていますが、別の方法です)

答えて

5

このコードは、PyPy上でうまく動作することに注意してください(実際には、これらの2つの関数型の間に実際の区別はありません)。

(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,)) 
>>>> 
関連する問題