mirror of https://github.com/TwoWater/Python
106 lines
3.9 KiB
Markdown
106 lines
3.9 KiB
Markdown
# 二、模块的使用 #
|
||
|
||
## 1、import ##
|
||
|
||
Python 模块的使用跟其他编程语言也是类似的。你要使用某个模块,在使用之前,必须要导入这个模块。导入模块我们使用关键字 `import`。
|
||
|
||
`import` 的语法基本如下:
|
||
|
||
```python
|
||
import module1[, module2[,... moduleN]
|
||
```
|
||
|
||
比如我们使用标准库模块中的 math 模块。当解释器遇到 `import` 语句,如果模块在当前的搜索路径就会被导入。
|
||
|
||
```python
|
||
#!/usr/bin/env python3
|
||
# -*- coding: UTF-8 -*-
|
||
|
||
import math
|
||
|
||
_author_ = '两点水'
|
||
|
||
print(math.pi)
|
||
```
|
||
|
||
输出的结果:
|
||
|
||
```txt
|
||
3.141592653589793
|
||
```
|
||
|
||
一个模块只会被导入一次,不管你执行了多少次 import。这样可以防止导入模块被一遍又一遍地执行。
|
||
|
||
当我们使用 import 语句的时候,Python 解释器是怎样找到对应的文件的呢?
|
||
|
||
这就涉及到 Python 的搜索路径,搜索路径是由一系列目录名组成的,Python 解释器就依次从这些目录中去寻找所引入的模块。这看起来很像环境变量,事实上,也可以通过定义环境变量的方式来确定搜索路径。搜索路径是在 Python 编译或安装的时候确定的,安装新的库应该也会修改。搜索路径被存储在sys 模块中的 path 变量 。
|
||
|
||
因此,我们可以查一下路径:
|
||
|
||
```python
|
||
#!/usr/bin/env python
|
||
# -*- coding: UTF-8 -*-
|
||
|
||
import sys
|
||
|
||
print(sys.path)
|
||
```
|
||
|
||
输出结果:
|
||
|
||
|
||
```txt
|
||
['C:\\Users\\Administrator\\Desktop\\Python\\Python8Code', 'G:\\PyCharm 2017.1.4\\helpers\\pycharm', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages', 'C:\\Users\\Administrator\\Desktop\\Python\\Python8Code\\com\\Learn\\module\\sys']
|
||
|
||
```
|
||
|
||
## 2、from···import ##
|
||
|
||
|
||
有没有想过,怎么直接导入某个模块中的属性和方法呢?
|
||
|
||
Python 中,导入一个模块的方法我们使用的是 `import` 关键字,这样做是导入了这个模块,这里需要注意了,这样做只是导入了模块,并没有导入模块中具体的某个属性或方法的。而我们想直接导入某个模块中的某一个功能,也就是属性和方法的话,我们可以使用 `from···import` 语句。
|
||
|
||
语法如下:
|
||
|
||
```python
|
||
from modname import name1[, name2[, ... nameN]]
|
||
```
|
||
|
||
看完简介后可能会想, `from···import` 和 `import` 方法有啥区别呢?
|
||
|
||
想知道区别是什么,观察下面两个例子:
|
||
|
||
`import` 导入 sys 模块,然后使用 version 属性
|
||
|
||

|
||
|
||
`from···import` 直接导入 version 属性
|
||
|
||

|
||
|
||
## 3、from ··· import * ##
|
||
|
||
通过上面的学习,我们知道了 `from sys import version` 可以直接导入 version 属性。但是如果我们想使用其他的属性呢?比如使用 sys 模块中的 `executable` ,难道又要写多一句 `from sys import executable` ,两个还好,如果三个,四个呢?难道要一直这样写下去?
|
||
|
||
这时候就需要 `from ··· import *` 语句了,这个语句可以把某个模块中的所有方法属性都导入。比如:
|
||
|
||
```python
|
||
#!/usr/bin/env python3
|
||
# -*- coding: UTF-8 -*-
|
||
|
||
from sys import *
|
||
|
||
print(version)
|
||
print(executable)
|
||
|
||
```
|
||
|
||
输出的结果为:
|
||
|
||
```txt
|
||
3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)]
|
||
C:\Users\Administrator\AppData\Local\Programs\Python\Python36\python.exe
|
||
```
|
||
|
||
注意:这提供了一个简单的方法来导入一个模块中的所有方法属性。然而这种声明不该被过多地使用。 |