【编程语言学习——python】10模块

定义、导入、测试模块

先敲入代码,保存.py文件至自定路径中

def hello():
    print ("Hello,world!")

def test():##用于测试函数是否编写正确
    hello()

继而设定路径、导入模块及应用模块中的函数。

>>> import sys
>>> sys.path.append('C:/python')
>>> import hello3
>>> hello3.test()
Hello,world!
>>> hello3.hello()
Hello,world!

包 :可以存储其他模块,但需包含一个名字为_init_.py的文件。

>>>import drawing##导入drawing包,除了_init_其余模块不可用。
>>>import drawing.colors##导入colors模块,只能全名使用该模块。
>>>from drawing import sharpes##导入sharpes模块,可以短名使用。

探究模块

  • 查看模块里的内容
>>> import copy
>>> print(dir(copy))##查看所有对象
>>> [n for n in dir(copy) if not n.startswith('_')]##列表推导式查看不带下划线(不用于被外部使用)的对象。
  • 帮助与文档
>>> 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.
>>> print(copy.copy.__doc__)
Shallow copy operation on arbitrary Python objects.

    See the module's __doc__ string for more info.
  • 查看源代码
>>> print(copy.__file__)##寻找源代码所在路径
C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\copy.py

一些常用模块

  • fileinput
  • 集合、堆(heapq)、双端队列(deque)
  • time
  • random
  • re

猜你喜欢

转载自blog.csdn.net/xiangshiyi0724/article/details/84963082