对pygtk3的反思可能吗?

2024-05-02 03:01:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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和automaticall generated pygobject bindings,在我尝试的所有示例中,我只能得到(*args, **kwargs)作为每个gtk方法的参数。在

示例:Label.set_文本which requires a string

^{pr2}$

现在的问题是:这是(python绑定的方法内省的损失)一旦pygobjects(文档)的工作投入到pygobjects中,就会发生改变吗?还是因为pygobjects的工作方式,这种情况会一直存在吗?在


Tags: orofthe方法函数log示例base
3条回答

现在,我想这还没准备好。但是,您仍然可以手动查看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标记,该标记又包含一些{}标记,这些标记用于按名称、描述和类型描述每个参数:

<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>

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

我相信这就是创建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

唯一的方法(据我所知)是查看内置函数的方法参数,就是查看doc字符串。在

^{pr2}$

我编写了自己的C python模块,并寻找了“修复”(…)的方法,解决方法是将它放在doc字符串中,我认为这很容易出错,因为每次更改函数时都要更新doc字符串。在

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

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

另一个有用的工具是pydoc:

pydoc gi.repository.Gtk

相关问题 更多 >