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_text which requires a string
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的工作方式而一直存在的东西?
发布于 2011-11-10 20:00:54
现在,我认为这还没有准备好。但是,您仍然可以查看Gtk-3.0.gir文件(在我系统中位于/usr/share/gir-1.0/Gtk-3.0.gir中)进行手动内省。
gir文件只是一个xml文件,不管您使用的是哪种编程语言,都应该使用它来探索公开的接口。例如,可以找到查找<class name="Label"的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-10-25 00:28:46
我相信这将是创建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模块,并且一直在寻找“修复”(...)的方法。解决办法是将它放在doc字符串中,我认为这很容易出错,因为每次更改函数时都必须更新doc字符串。
发布于 2011-11-01 20:05:45
您可以使用其他内置函数,如dir()、vars()等。
http://docs.python.org/library/functions.html
另一个有用的工具是pydoc:
pydoc gi.repository.Gtkhttps://stackoverflow.com/questions/7859490
复制相似问题