如何获取内置Python类构造函数的参数列表?
我正在尝试使用 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,))
这个则不行:
>>> 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 项目源代码中看到的一些代码来初始化 AST 节点,但我在想是否还有其他方法。)
2 个回答
9
请注意,这段代码在PyPy上运行得很好,因为在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,))
>>>>
9
这些东西是无法获取的,因为它们是函数背后的C代码的属性,而不是函数本身的属性。