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.常量”符进行调用,为什么呢?因为上面那句红色(英语)的话。

  

原文地址:https://www.cnblogs.com/Cirgo/p/8417490.html