如何获取内置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 节点,但我想知道是否还有其他方法)
I'm trying to use the inspect
module, however it seems I can't use it on a built-in (native?) class, or else I misunderstood.
I'm using Python 2.7 and tried with Python 3.2.
This is working:
>>> 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,))
This is not working:
>>> 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
I am wondering if there is another technique to get these parameters automatically?
(In my case, I think about an alternative which would be to parse the Python grammar, the ASDL file which explain how to init AST nodes using some code I saw in PyPy Project's source, but I'm wondering if there is another way)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无法获取它们,因为它们是 函数背后的C代码,而不是函数本身。
There is no way to get them, as they are a property of the C code behind the function, and not of the function itself.
请注意,这段代码在 PyPy 上运行得很好(这两种函数类型之间没有真正的区别)。
Note that this code works just fine on PyPy (where there is no really distinction between those two function types).