【Python基础10】探索模块

1 模块包含什么

1.1 使用dir

函数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']
>>> 

1.2 变量__all__

__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

2 使用help获取帮助

>>> 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模块的所有信息

3 文档

文档是有关模块信息的自然来源。
如果你想查看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).
>>> 

4 使用源码

一种方法是通过sys.path来查找,但更快捷的方式是查看模块的特性__file__。

>>> print(copy.__file__)
C:\Users\sudeli\AppData\Local\Programs\Python\Python37-32\lib\copy.py
>>>

如果是.pyc结尾的可以查看以.py结尾的相应文件。
注意有些模块的源代码你可能完全无法读懂。他们可能是解析器的一部分(如模块sys),还可能是使用C语言编写的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值