函数dir会列出对象的所有属性(对于模块,列出所有的函数、类、变量等)
>>> import copy
>>> dir(copy)
['Error', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_copy_dispatch', '_copy_immutable', '_deepcopy_atomic', '_deepcopy_dict', '_deepcopy_dispatch', '_deepcopy_list', '_deepcopy_method', '_deepcopy_tuple', '_keep_alive', '_reconstruct', 'copy', 'deepcopy', 'dispatch_table', 'error']
>>> [ n for n in dir(copy) if not n.startswith('_') ]
['Error', 'copy', 'deepcopy', 'dispatch_table', 'error']
>>>
__all__旨在定义模块的公有接口。
>>> copy.__all__
['Error', 'copy', 'deepcopy']
>>>
它是在模块cop中像下面这样定义的
__all__ = ['Error', 'copy', 'deepcopy']
它告诉这个模块导入所有的名称意味着什么
from copy import *
只能得到变量__all__中列出的3个函数[‘Error’, ‘copy’, ‘deepcopy’];
如果想导入其他函数必须显示的导入,比如想使用’dispatch_table’
import copy
copy.dispatch_table
或者
from copy import dispatch_table
dispatch_table
>>> help(copy.copy)
Help on function copy in module copy:
copy(x)
Shallow copy operation on arbitrary Python objects.
See the module's __doc__ string for more info.
>>>
如果直接使用help(copy)会打印copy模块的所有信息
文档是有关模块信息的自然来源。
如果你想查看range的描述可以直接查看其文档信息:
>>> print(range.__doc__)
range(stop) -> range object
range(start, stop[, step]) -> range object
Return an object that produces a sequence of integers from start (inclusive)
to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.
start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.
These are exactly the valid indices for a list of 4 elements.
When step is given, it specifies the increment (or decrement).
>>>
一种方法是通过sys.path来查找,但更快捷的方式是查看模块的特性__file__。
>>> print(copy.__file__)
C:\Users\sudeli\AppData\Local\Programs\Python\Python37-32\lib\copy.py
>>>
如果是.pyc结尾的可以查看以.py结尾的相应文件。
注意有些模块的源代码你可能完全无法读懂。他们可能是解析器的一部分(如模块sys),还可能是使用C语言编写的。