[英]How to get arguments list of a built-in Python class constructor?
我正在尝试使用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 Project的源代码中看到的代码来初始化AST节点,但我想知道是否还有其他方法)
没有办法获得它们,因为它们是函数背后的C代码的属性,而不是函数本身的属性。
请注意,此代码在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,))
>>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.