【问题标题】:How to get arguments list of a built-in Python class constructor?如何获取内置 Python 类构造函数的参数列表?
【发布时间】:2011-10-02 17:41:08
【问题描述】:

我正在尝试使用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 语法,即解释如何使用我在 PyPy 项目源代码中看到的一些代码来初始化 AST 节点的 ASDL 文件,但我想知道是否有另一种方式)

【问题讨论】:

    标签: python reflection inspection asdl


    【解决方案1】:

    无法获取它们,因为它们是the C code behind the function 的属性,而不是函数本身的属性。

    【讨论】:

      【解决方案2】:

      请注意,此代码在 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,))
      >>>> 
      

      【讨论】:

        猜你喜欢
        • 2012-09-29
        • 1970-01-01
        • 1970-01-01
        • 2017-09-14
        • 2016-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多