8

python 的一大优点是能够对方法和函数进行自省。例如,要获取math.log您可以(在 ipython 中)运行的函数签名:

In [1]: math.log?
Type:       builtin_function_or_method
Base Class: <type 'builtin_function_or_method'>
String Form:    <built-in function log>
Namespace:  Interactive
Docstring:
    log(x[, base])

    Return the logarithm of x to the given base.
    If the base not specified, returns the natural logarithm (base e) of x.

并且看到x和可选base的是这个函数的参数。

使用新的 gtk3 和自动生成的 pygobject bindings,我可以在我尝试的所有示例中只获取(*args, **kwargs)每个 gtk 方法的参数。

示例:Label.set_text需要一个字符串

In [1]: from gi.repository import Gtk
In [2]: mylabel = Gtk.Label("hello")
In [3]: mylabel.set_text?
Type:       instancemethod
Base Class: <type 'instancemethod'>
String Form:    <bound method Label.set_text of <Label object at 0x275b230 (GtkLabel at 0x28cd040)>>
Namespace:  Interactive
File:       /usr/lib/python2.7/dist-packages/gi/types.py
Definition: L.set_text(*args, **kwargs)
Docstring:
    <no docstring>

现在的问题:这(python 绑定的方法自省的丢失)是否会再次改变(文档)工作已经进入 pygobjects 或者由于 pygobjects 的工作方式而保留下来的东西?

4

3 回答 3

4

现在,我认为这还没有准备好。但是,您仍然可以手动检查Gtk-3.0.gir文件(在我的系统中/usr/share/gir-1.0/Gtk-3.0.gir)。

gir 文件只是一个 xml 文件,无论您使用哪种编程语言,它都应该用于探索暴露的界面。例如,Label可以找到类来寻找<class name="Label". 在class标签内有一个doc标签,其中包含有关此小部件应该做什么的大量信息。还有很多method标签,其中一个是您对您的示例感兴趣的标签:<method name="set_text". 在这个method标签内,不仅有一个doc描述方法的标签,还有一个parameters标签,该标签又包含一些parameter标签,用于根据名称、描述和类型来描述每个参数:

<parameters>
  <parameter name="str" transfer-ownership="none">
    <doc xml:whitespace="preserve">The text you want to set</doc>
    <type name="utf8" c:type="gchar*"/>
  </parameter>
</parameters>

所以所有的信息都已经存在了。

于 2011-11-10T12:00:53.657 回答
0

我相信这将是用于创建 python 模块的 C API 的方式。例如:

>>> import inspect
>>> inspect.getargspec(math.log)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\inspect.py", line 813, in getargspec
    raise TypeError('{!r} is not a Python function'.format(func))
TypeError: <built-in function log> is not a Python function

唯一的方法(据我所知)是查看内置函数的方法参数是查看文档字符串。

>>> help(math.log)
Help on built-in function log in module math:

log(...)
    log(x[, base])

    Return the logarithm of x to the given base.
    If the base not specified, returns the natural logarithm (base e) of x.

我已经编写了自己的 C python 模块,并寻找“修复” (...) 的方法,解决方法是将它放在我认为容易出错的文档字符串中,因为我必须更新文档每次我更改函数时字符串。

于 2011-10-24T16:28:46.287 回答
0

您可以使用其他内置函数,如 dir()、vars() 等。

http://docs.python.org/library/functions.html

另一个有用的工具是 pydoc:

pydoc gi.repository.Gtk
于 2011-11-01T12:05:45.363 回答