高效使用 IPython:技巧与魔法命令全解析
1. 快速访问文档与源代码
在 Python 编程中,通过文档字符串(docstrings)能快速访问文档,这也是我们应养成在代码中添加内联文档习惯的原因之一。同时,IPython 提供了一个强大的功能——使用双问号(??)访问对象的源代码。
例如,定义一个简单的函数 square
:
def square(a):
"Return the square of a"
return a ** 2
在 IPython 中,使用 square??
可以查看其源代码:
In [8]: square??
Type: function
String form: <function square at 0x103713cb0>
Definition: square(a)
Source:
def square(a):
"Return the square of a"
return a ** 2
不过,当对象不是用 Python 实现,而是用 C 或其他编译扩展语言实现时, ??
后缀可能不会显示源代码,此时它与 ?
后缀输出相同,如 Python 的内置函数 len
: