01Python基础_08模块和包

  1. 模块

  Python会将所有 .py 结尾的文件认定为Python代码文件,如:ex1.py。可以使用import关键词加载并执行它(这里要求ex1.py在当前工作目录):

  ex1.py内容:

PI = 3.1416

def sum(lst):
    tot = lst[0]
    for value in lst[1:]:
        tot = tot + value
    return tot
    
w = [0, 1, 2, 3]
print sum(w), PI
View Code

  1. 加载模块

import ex1

  在导入时,Python会执行一遍模块中的所有内容。ex1.py 中所有的变量都被载入了当前环境中。

  可以使用别名加载模块:

import ex1 as e1
e1.PI

out: 3.1416

  2. 查看或修改模块里的变量

  可使用 “ex1.变量名” 的形式来查看或者修改这些变量:

print ex1.PI
ex1.PI = 3.141592653
print ex1.PI

out: 3.1416

  3.141592653

  3. 调用模块里的函数

  也可以使用 “ex1.函数名” 的形式调用模块里的函数:

print ex1.sum([2, 3, 4])

out: 9

  注:为了提高效率,Python只会载入模块一次,已经载入的模块再次载入时,Python并不会真正执行载入操作,哪怕模块的内容已经改变。需要重新导入模块时,可以使用reload强制重新载入它:

reload(ex1)

out: 6 3.1416

  4. __name__ 属性

  一个 .py 文件既当作脚本,又能当作模块用,当文件被当作脚本执行的时候, __name__的值才会是 '__main__'

  ex2.py:

PI = 3.1416

def sum(lst):
    """ Sum the values in a list
    """
    tot = 0
    for value in lst:
        tot = tot + value
    return tot

def add(x, y):
    " Add two values."
    a = x + y
    return a

def test():
    w = [0,1,2,3]
    assert(sum(w) == 6)
    print 'test passed.'
    
if __name__ == '__main__':
    test()
View Code
run ex2.py

out: test passed.

  当当作模块导入,test()不会执行:

import ex2

  5. 其他导入方法

  从模块中导入变量:

from ex2 import add, PI    #导入后,可以直接使用 add , PI

  导入全部变量:

from ex2 import *

  这种导入方法不是很提倡,因为如果你不确定导入的都有哪些,可能覆盖一些已有的函数。

  2. 包

  假设有这样的一个文件夹:

foo/

  • __init__.py
  • bar.py
  • baz.py

  这意味着 foo 是一个包,我们可以这样导入其中的内容:

from foo.bar import func
from foo.baz import zap

注:导入包要求:

  • 文件夹 fooPython的搜索路径中。(Python的搜索路径可以通过环境变量PYTHONPATH设置)
  • __init__.py 表示 foo 是一个包,它可以是个空文件。

  3. 常用标准库

  • re 正则表达式
  • copy 复制
  • math, cmath 数学
  • decimal, fraction
  • sqlite3 数据库
  • os, os.path 文件系统
  • gzip, bz2, zipfile, tarfile 压缩文件
  • csv, netrc 各种文件格式
  • xml
  • htmllib
  • ftplib, socket
  • cmd 命令行
  • pdb
  • profile, cProfile, timeit
  • collections, heapq, bisect 数据结构
  • mmap
  • threading, Queue 并行
  • multiprocessing
  • subprocess
  • pickle, cPickle
  • struct
原文地址:https://www.cnblogs.com/zhangyide/p/8204730.html