如何获取内置Python类构造函数的参数列表?

Jul*_*cke 9 python reflection inspection asdl

我正在尝试使用该inspect模块,但似乎我不能在内置(本机?)类中使用它,否则我误解了.

我正在使用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,))
Run Code Online (Sandbox Code Playgroud)

这不起作用:

>>> 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
Run Code Online (Sandbox Code Playgroud)

我想知道是否有另一种技术可以自动获取这些参数?

(在我的例子中,我想到了一个解析Python语法的替代方案,ASDL文件解释了如何使用我在PyPy Project的源代码中看到的代码来初始化AST节点,但我想知道是否还有其他方法)

Ign*_*ams 9

没有办法获得它们,因为它们是函数背后的C代码的属性,而不是函数本身的属性.


fij*_*jal 6

请注意,此代码在PyPy上运行得很好(这两种函数类型之间没有真正的区别).

(pypy)fijal@helmut:~$ 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,))
>>>> 
Run Code Online (Sandbox Code Playgroud)