python学习笔记13(模块、包)

在Python中有一个概念叫做模块(module),比如在Python中要调用sqrt函数,必须用import关键字引入math这个模块,下面就来了解一下Python中的模块。

模块文件以.py后缀结尾,文件名不要与保留字重名。    例如:aname.py     文件名为aname模块的Python代码。

一、模块的引入:

在Python中用关键字import来引入某个模块,比如要引用模块math,就可以在文件最开始的地方用import math来引入。在调用math模块中的函数时,必须这样引用:模块名.函数名

>>> import math            # 引入math模块
>>> print math.sqrt(4) # 调用函数必须加上模块名
2.0

有时候我们只需要用到模块中的某个函数,只需要引入该函数即可,此时可以通过语句下面的语句来实现

  from 模块名 import 函数名1,函数名2....

from fib import fibonacci     # 导入模块 fib 中的 fibonacci 功能

如果想一次性引入math中所有的东西,还可以通过from math import *来实现,但是不建议这么做。

from modname import *   

二、定义自己的模块

  在Python中,每个Python文件都可以作为一个模块,模块的名字就是文件的名字。

  比如有这样一个文件test.py,在test.py中定义了函数add:

#test.py

def add(a,b):
return a+b

那么在其他文件中就可以先import test,然后通过test.add(a,b)来调用了,当然也可以通过from test import add来引入。

三、模块导入的特征:

(1)、载入时执行模块,也就是导入模块的顶层代码将会被执行,通常包括该模块内全局变量类和函数的声明

(2)、一个模块可被导入(import)多次,但是只加载(load)一次

为什么要使用模块?
  1、代码重用。
  2、系统名字空间的划分,是组织系统组件的工具。
  3、实现服务或数据的共享,只要一个模块,就可以被多个客户导入。

python 中的包

1、包的概念

包是一个有层次的文件目录结构,由模块和子包组成。

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQEAAAEXCAIAAAAiAWYsAAAZRklEQVR4nO2d63cWRZ7Hm79g3uzRPb4YFBfl4q4KzHrWUcHRHZE9O6gsmcSDDBcVGcRJHBkIO7OYcHC4uSugGHWIUTcIyk043OQSEkwgiAJhBoLoYkCUW2YCIXli8jzUvmhp+um69K26u7r7+zl1crr76aqu7qe+9a16un9pjQCQbrSoKwBAxEADIO1AAyDtyNTAwVUz81dLCSGkp21gQa+BH/Qa+EGvXV/uIj1tEo8I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qJWXeqlA8ghiYZwAcIiU8MjZaPrAL9lxNrYnb+iviAtxgaWa1WYmkSy4kv8AFCwoqhkagBiQ0XGojZ+avgA95iaOgHnunn3piDHMEDc5a8gsPR5TjcJw3ABwgJJYaGeIqG4S1YGm5ACykhZmergg8QTzE0hKMB29ZMd/y8Yr3tY2spiQc+QEgoMTSE0zQd9uhO9pGeKyXE7LQV8QEdtzE0hN/ozZ8KNmr5MD/lFSUoWZArDcAHCInuPjFzdARCJmYXXSkf8IO4vwdhAh8gBM8LpZuY9TqJ8QGgDvABQuAD6QYaIAQaSDcxG1JgLASkAx8gBD6QbmLWnSrlA4ihSQbwAULCiqFx+Nt/mDcKcEeCwAe8Edx7aMJvkdAAfIAQld5DAw2ET8zOXwUf8BNDY1l1vpFXFDMLYQ2ovO2TBuADhCgTQ+NknzAXUkLMzlYFHyBSY2iIew1Y+m8njdhh0w9zOq4O8AFCIoqh8ekDsvZJbfdvELPTVsQHdFzF0NCdt7FqWXA1jmeWQx9OXI4gVxqADxCC+8TpJmaKV8oHQDKADxACH0g3MetO4QNAOvABQuAD6QYaIAQaSDcxG1JgLASkAx8gBD6QbmLWnSrlA4ihSQbwAUKCj6HxdvM1nXdtwydm11cRH/AQQ8Nsyk7aNzQQNPABQkKJoYEGlCVm11cFH5DyHhp6C/OBOQINBA98gJBQYmiYjyjTy+a/9D4gCGJ2fVXwAeIphgYaUBb4gBc8xNBAA8oSs+uriAZ0nMfQ8CJdzKvMv7xJApAIfACkHTQlkHZi5gMASAc+ANIOfACkHWgApB2MhUDagQZA2oEGQNqBBkDagQZA2vl/bXI+TOCO1IcAAAAASUVORK5CYII=" alt="" />

2、解析包机制:

每一个.py文件称为一个module,module之间可以互相导入,module可以定义在包里面,Python定义包的方式稍微有点古怪,假设我们有一个parent文件夹,该文件夹有一个child子文件夹,child中有一个module a.py,如何让Python知道这个文件层次结构?很简单,每个目录都放一个名为 _init_.py 的文件,该文件内容可以为空,这个层次结构同上。

3、python中__init__.py文件的作用

python的每个模块的包中,都有一个__init__.py文件,有了这个文件,我们才能导入这个目录下的module。
那么,__init__.py还有什么别的功能呢?
其实,__init__.py里面还是可以有内容的,我们在导入一个包时,实际上导入了它的__init__.py文件。
python的每个模块的包中,都有一个__init__.py文件,有了这个文件,我们才能导入这个目录下的module。
 
其实,__init__.py里面还是可以有内容的,我们在导入一个包时,实际上导入了它的__init__.py文件,我们可以再__init__.py文件中再导入其他的包,或者模块。
这样,当我们导入这个包的时候,__init__.py文件自动运行。帮我们导入了这么多个模块,我们就不需要将所有的import语句写在一个文件里了,也可以减少代码量。
上一篇:R语言基础1


下一篇:常看常遇见之一——BS架构VS CS架构