1. 程式人生 > >Python中的import,from...import以及模組、包、庫的概念

Python中的import,from...import以及模組、包、庫的概念

 首先,說明一下,我使用的是python3.6.3win32版本,使用的IDE是pycharm2017社群免費版。

  剛開始接觸python程式設計不久,有很多概念都不是特別清楚,但是我覺得既然選擇,儘自己最大努力做到最好吧。這幾天在玩python的一個開源框架(也就是庫)pygame,特別好玩,而且製作2D小遊戲很簡單。不過都是比著別人的例子敲程式碼,實驗遊戲效果,漸漸的,想自己創造自己的遊戲了,所以有一些問題咱們必須趁早搞醒合,弄懂!

  pygame,被稱作一個庫,當然也有人說這是一個框架,兩者都沒錯!既然提到‘庫’的概念,那麼這裡先講一下,模組、包、庫的糾紛。

       模組:就是指以.py為字尾名的檔案

  包:就和Java中的包一樣,包下面可以有多級子包,每個包中可以有任意個(包含0)模組。就和windows中的資料夾概念一樣。

  庫:其實和上面兩者沒有什麼關係。能解決同一類問題模組的集合就可以叫做庫,庫中包含模組的個數可以是1個或者2個...具體看待解決問題的大小以及編寫庫的程式設計師對模組的具體劃分。例如:pygame庫中,就有處理音訊、視訊、滑鼠事件等等的模組,具體模組可以參照       www.pygame.org/docs/#   文件說明。

  講清楚了上面三個概念,那麼匯入的時候,我們得遵循什麼技巧呢?

   那麼,重點來了,我經過實驗以及到處查閱了一些資料(畢竟新手),得出來一下兩個結論:

   import xxx.xxx 的落腳點一定是模組,這句話什麼意思呢?就是說xxx.xxx的最後一級一定是.py的檔名。且以這種方式匯入的模組呼叫方式,必須是“模組名.xxx”,xxx可能是函式,常量等等。

   但是有時候只需要匯入模組中的某些部分。那麼我們就是用:

   from 模組名 import xxx ,xxx可以是類,函式,常量等等。注意模組名可能是什麼包下面的模組,形如:xxx.xxx。

   為什麼把這個寫成一篇部落格,直接原因如下:

   pygame庫中有一個模組,pygame.locals這個模組裡面全是一些常量(constants),一般都會匯入進去。先來分析一下,pygame.locals的結構,“pygame.locals”中的“pygame”是一個包名,實際上,這個包下面還有很多模組,還有子包mixer(同時還有pygame.mixer模組,這裡的mixer說明在pygame資料夾下面有一個mixer.py的檔案,子包mixer說明有一個mixer的資料夾)。但是要注意的是(下面是這個模組官方說明文件):

 pygame.locals

pygame constants

This module contains various constants used by pygame. It’s contents are automatically placed in the pygame module namespace. However, an application can use pygame.localspygame constants to include only the pygame constants with a ‘from pygame.localspygame constants import *’.Detailed descriptions of the various constants are found throughout the pygame documentation. pygame.display.set_mode()Initialize a window or screen for display flags like HWSURFACE are found in the Display section. Event types are explained in the Event section. Keyboard K_ constants relating to the key attribute of a KEYDOWN or KEYUP event are listed in the Key section. Also found there are the various MOD_ key modifiers. Finally, TIMER_RESOLUTION is defined in Time.

 也就是說,如果我們匯入了pygame模組而不匯入pygame.locals這個模組,那麼我們可以使用“pygame.常量”符進行呼叫,為什麼呢?因為上面那句紅色(英語)的話。