如何获取内置Python类构造函数的参数列表?
我正在尝试使用如何获取内置Python类构造函数的参数列表?,python,reflection,inspection,asdl,Python,Reflection,Inspection,Asdl,我正在尝试使用inspect模块,但似乎无法在内置(本机?)类上使用它,否则我就误解了 我正在使用Python2.7,并尝试使用Python3.2 这是有效的: >>> import inspect >>> class C: ... def __init__(self,a,b=4): ... self.sum = a + b ... >>> inspect.getargspec(C.__init__) ArgSpec
inspect
模块,但似乎无法在内置(本机?)类上使用它,否则我就误解了
我正在使用Python2.7,并尝试使用Python3.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
导入检查
>>>导入ast
>>>inspect.getargspec(ast.If.\uuuu init\uuuu)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
getargspec中的文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py”,第813行
raise TypeError(“{!r}不是Python函数”。format(func))
TypeError:不是Python函数
我想知道是否有其他技术可以自动获取这些参数
(在我的例子中,我想另一种方法是解析Python语法,ASDL文件解释如何使用我在PyPy项目源代码中看到的一些代码初始化AST节点,但我想知道是否还有其他方法)无法获取它们,因为它们是,而不是函数本身。请注意,此代码在PyPy上运行良好(这两种函数类型之间没有真正的区别)
(pypy)fijal@helmut:~$python
C类(Python 2.7.1(f1e873c5533d,2011年9月19日,02:01:57)
linux2上的[PyPy 1.6.0-dev1和GCC 4.4.3]
有关详细信息,请键入“帮助”、“版权”、“信用证”或“许可证”。
欢迎来到RLCompleter20.96
要获得美好的体验,请多次点击
现在来看一个完全不同的例子:“‘PyPy需要一个及时的JIT’”
>>>>C类:
..定义初始值(self,a,b=4):
……通过
....
>>>>进口检验
>>>>inspect.getargspec(C.\uuuuu init\uuuuuuu)
ArgSpec(args=['self','a','b'],varargs=None,keywords=None,defaults=(4,))
>>>>
(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,))
>>>>