Python导入模块

示例

使用以下import语句:

>>> import random
>>> print(random.randint(1, 10))
4

import module将导入模块,然后允许您使用module.name语法引用其对象-例如,值,函数和类。在上面的示例中,random模块被导入,其中包含randint函数。因此,通过导入random可以调用randint用random.randint。

您可以导入模块并将其分配给其他名称:

>>> import random as rn
>>> print(rn.randint(1, 10))
4

如果您的python文件main.py位于和相同的文件夹中custom.py。您可以这样导入:

import custom

也可以从模块导入功能:

>>> from math import sin
>>> sin(1)
0.8414709848078965

要将特定功能更深入地导入模块中,点运算符只能在import关键字的左侧使用:

fromurllib.requestimport urlopen

在python中,我们有两种从顶层调用函数的方法。一个是import,另一个是from。import当我们可能发生名称冲突时,应使用。假设我们有一个hello.py文件和两个world.py文件具有相同的功能,名为function。然后import声明会很好。

from hello import function
from world import function

function() #世界的功能将被调用。不是你好

通常import会为您提供一个名称空间。

import hello
import world

hello.function() # 独家的hello函数将被调用 
world.function() # 专门调用世界的功能

但是,如果您有足够的把握,那么在您的整个项目中就无法使用相同的函数名称,而应该使用from语句

可以在同一行上进行多次导入:

>>> # 多个模块
>>> import time, sockets, random
>>> # 多种功能
>>> from math import sin, cos, tan
>>> # 多个常数
>>> from math import pi, e

>>> print(pi)
3.141592653589793
>>> print(cos(45))
0.5253219888177297
>>> print(time.time())
1482807222.7240417

上面显示的关键字和语法也可以组合使用:

>>> fromurllib.requestimport urlopen as geturl, pathname2url as path2url, getproxies
>>> from math import factorial as fact, gamma, atan as arctan
>>> import random.randint, time, sys

>>> print(time.time())
1482807222.7240417
>>> print(arctan(60))
1.554131203080956
>>> filepath = "/dogs/jumping poodle (december).png"
>>> print(path2url(filepath))
/dogs/jumping%20poodle%20%28december%29.png