知道答案并不重要,重要的是如何在不知道答案的情况下快速找到解决问题的方法。
一、在IPython中访问帮助文档 —— ? 和 help()函数
每一个Python对象都会包含一段doc string文字,大多数情况下这段文字会包含一个简短的对象概览和怎么使用这个对象的描述。Python有一个内建函数 help() 可以获得这段文字信息并输出。
- 查看内建函数的帮助文档
ipython In [1]: help(len) Help on built-in function len in module builtins: len(...) len(object) -> integer Return the number of items of a sequence or mapping.
ipython In [2]: len? Type: builtin_function_or_method String form: <built-in function len> Namespace: Python builtin Docstring: len(object) -> integer Return the number of items of a sequence or mapping.
- 查看某个对象的某个方法的帮助文档
ipython In [3]: L = [1, 2, 3] In [4]: L.insert? Type: builtin_function_or_method String form: <built-in method insert of list object at 0x1024b8ea8> Docstring: L.insert(index, object) -- insert object before index
- 查看对象本身的帮助文档
ipython In [5]: L? Type: list String form: [1, 2, 3] Length: 3 Docstring: list() -> new empty list list(iterable) -> new list initialized from iterable's items
- 查看自定义函数的帮助文档
ipython In [6]: def square(a): ....: """Return the square of a.""" ....: return a ** 2 ....: In [7]: square? Type: function String form: <function square at 0x103713cb0> Definition: square(a) Docstring: Return the square of a.
- ?几乎可以作用于任何对象
- 自定义函数时记得写doc string
二、在IPython中访问源代码 —— ??
ipython 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的内建对象上)
三、使用Tab键进行探索
- Tab键补全对象可使用的属性、方法
ipython In [10]: L.<TAB> L.append L.copy L.extend L.insert L.remove L.sort L.clear L.count L.index L.pop L.reverse In [10]: L.c<TAB> L.clear L.copy L.count In [10]: L.co<TAB> L.copy L.count
注:私有方法不会在表中列出,因为私有方法通常以__开头作为方法名,需要显式使用_将它显示出来。
- 在import引入模块或模块内的对象时使用Tab键补全
In [10]: from itertools import co<TAB> combinations compress combinations_with_replacement count In [10]: import <TAB> Display all 399 possibilities? (y or n) Crypto dis py_compile Cython distutils pyclbr ... ... ... difflib pwd zmq In [10]: import h<TAB> hashlib hmac http heapq html husl
- 通配符匹配 —— *
ipython In [10]: *Warning? BytesWarning RuntimeWarning DeprecationWarning SyntaxWarning FutureWarning UnicodeWarning ImportWarning UserWarning PendingDeprecationWarning Warning ResourceWarning In [10]: str.*find*? str.find str.rfind
注:之前的补全都是在我们知道我们要找的对象或属性的前几个字母时使用的,如果我们只知道中间的字母,或者最后的字母该怎么办呢?可以使用*这个符号。*可以匹配任何字符串,包括空字符。