1. 程式人生 > >【程式語言學習——python】10模組

【程式語言學習——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