任何语言使用已封装好的模块(或库)都要先进行导入,Python使用import关键字导入模块。
如何导入
导入模块
import somemodule
somemodule.func() # 调用somemodule中的func函数
导入一个或若干函数
from somemodle import func # 导入一个函数
from somemodle2 import func1, func2, func3 # 导入若干函数
from somemodule3 import * # 导入模块的所有函数
func() # 调用, 不必写模块名称
func1() # 调用
导入类
from somemodule import SomeClass
from somemodyle import Class1, Class2
避免冲突
如果导入的两个模块包含相同名称的函数就会产生冲突,比如都包含函数open, 这时候可以使用第一种方式导入两个模块,并使用一下方式调用:
module1.open()
module2.open()
导入重命名
对导入的对象进行重命名,可以简化名称,也可以用来解决名字冲突的问题。重命名实用as关键字。
import math as m
m.sqrt(2)
from math import sqrt as mysqrt
mysqrt(4)
from module1 import open as open1
from module2 import open as open2
open1()
open2()
包
一些关系紧密的功能分散在很多的模块中,可以把这些分散的模块组织为包(package)。包其实是另一种模块,它可以包含其他模块。模块存储在扩展名为.py的文件中,而包则是一个目录。要被Python视为包,目录必须包含文件init.py。
一个简单的例子,包名称drawing,其中包含模块shapes 和colors,目录结构如下:
drawing
┣ colors.py
┣ shapes.py
┗ __init__.py
__init__.py
文件:
"""Package drawing"""
PI = 3.14
colors.py
文件:
"""Define some colors"""
RED = "#FF0000"
GREEN = "#00FF00"
BLUE = "#0000FF"
shapes.py
文件:
"""Methods of drawing shapes """
def draw_line():
"""Draw line."""
print("draw line.")
def draw_rect():
"""Draw rectangle."""
print("draw rectangle")
导入包
使用import drawing
导入包,并尝试访问colors模块和shapes模块:
import drawing
print(drawing.__version__)
print(drawing.colors.BLUE)
drawing.shapes.draw_line()
输出:
3.14
Traceback (most recent call last):
File "lesson_7.py", line 5, in <module>
print(drawing.colors.BLUE)
AttributeError: module 'drawing' has no attribute 'colors'
可以看到,仅仅输出PI的值。也就是说import drawing
仅仅是导入drawing包(模块)即init.py的内容,它的子模块没有导入。
通过验证,from drawing import *
也是一样的效果。
显式导入子模块
import drawing
from drawing import colors, shapes
print(drawing.PI)
print(colors.BLUE)
shapes.draw_line()
输出:
3.14
#0000FF
draw line.
__all__
魔法变量
修改init.py文件:
"""Package drawing"""
PI = 3.14
__all__ = ['shapes']
为了验证all变量的作用,这里值添加shapes,不添加colors。
现在使用from drawing import *
导入包:
from drawing import *
shapes.draw_line()
print(colors.BLUE)
输出:
draw line.
Traceback (most recent call last):
File "lesson_7.py", line 4, in <module>
print(colors.BLUE)
NameError: name 'colors' is not defined
成功导入了shapes,colors没有导入,这说明all变量起作用了。
新的问题:这时候如果去访问 drawing.PI
, 会发现抛出未定义的异常,这是因为我们在__all__
规定中规定了导出的内容,显然__all__
中并不包括PI
。
在这个例子中我们应该对__all__
进行赋值:
__all__ = ['PI', shapes', 'colors']
为__all__
赋值旨在定义模块的公有接口。具体地说,它告诉解释器从这个模块导入所有的名称意味着什么。
编写模块时,像这样设置all 也很有用。因为模块可能包含大量其他程序不需要的变量、函数和类,比较周全的做法是将它们过滤掉。如果不设置all ,则会在以import * 方式导入时,导入所有不以下划线打头的全局名称。
网友评论