Skip to content

动态对象自省

内省(Introspection)是指在运行时(runtime)检查对象的属性。IPython 提供了强大且便捷的工具,用于快速检查 Python 对象,这对于交互式探索和调试(debugging)来说是无价的。

在对象名称后面输入问号(?)可以显示该对象的基本信息,包括其类型(type)、字符串表示(string representation),以及最重要的文档字符串(docstring)(如果存在)。

In [1]: import numpy as np
In [2]: data = np.array([10, 20, 30])
In [3]: data?
# 输出:
# Type: ndarray
# String form: [10 20 30]
# Length: 3
# File: .../numpy/core/records.py
# Docstring: ndarray(shape, dtype=float, buffer=None, offset=0, ...)
# An array object represents a multidimensional, homogeneous array...
# [... 完整文档字符串 ...]

这适用于变量、函数、类、模块——基本上任何 Python 对象。

In [4]: def calculate(a, b=1):
...: """Calculates a simple result."""
...: return (a + 1) * b
...:
In [5]: calculate?
# 输出:
# Signature: calculate(a, b=1)
# Docstring: Calculates a simple result.
# File: <ipython-input-4-...>
# Type: function

使用 ?? 获取更多细节(包括源代码)

Section titled “使用 ?? 获取更多细节(包括源代码)”

使用两个问号(??)可以提供更多详细信息。如果对象是在 Python 中定义的(而非编译后的 C 代码),?? 还会显示其源代码(source code)。

In [6]: calculate??
# 输出:
# Signature: calculate(a, b=1)
# Docstring: Calculates a simple result.
# Source:
# def calculate(a, b=1):
# """Calculates a simple result."""
# return (a + 1) * b
# File: <ipython-input-4-...>
# Type: function

对于内建函数(built-in functions)或在 C 扩展(C extensions)(如许多 NumPy 函数)中实现的对象,?? 通常会显示与 ? 相同的信息,因为其源代码无法直接获取。

你可以使用通配符(*)结合 ? 或 ?? 在当前命名空间(namespace)或对象的属性(attributes)中搜索匹配特定模式的名称。

In [7]: import os
In [8]: os.*path*?
# 输出:列出 os 模块中包含 'path' 的名称
# os.defpath
# os.get_exec_path
# os.path
# os.pathconf
# os.pathconf_names
# os.pathsep
# os.supports_unicode_filenames

对象内省(Introspection)与 Tab 补全(Tab completion)功能相辅相成。虽然 Tab 键可以帮助你发现对象有哪些属性(attributes)或方法(methods),但 ? 和 ?? 则帮助你理解它们 做什么 以及 如何实现。