module模块和包(十七)

在前面的几个章节中我们脚本上是用 python 解释器来编程,如果你从 Python 解释器退出再进入,那么你定义的所有的方法和变量就都消失了。

为此 Python 提供了一个办法,把这些定义存放在文件中,为一些脚本或者交互式的解释器实例使用,这个文件被称为模块。

模块是一个包含所有你定义的函数和变量的文件,其后缀名是.py。模块可以被别的程序引入,以使用该模块中的函数等功能。

这也是使 用  python 标准库的方法。

模块一共三种:

1.python标准库

2.第三方模块

3.应用程序自定义模块

 作用:

1. 执行对应的文件

2.引入文件的变量

import 会将导入的文件代码执行一遍,故我们只在对应的文件中定义函数,不做逻辑上的一些执行语句

一个模块只会被导入一次,不管你执行了多少次import。这样可以防止导入模块被一遍又一遍地执行。

当解释器遇到 import 语句,如果模块在当前的搜索路径就会被导入。

support.py 文件代码

#!/usr/bin/python3
# Filename: support.py
 
def print_func( par ):
    print ("Hello : ", par)
    return
test.py 文件代码

#!/usr/bin/python3
# Filename: test.py
 
# 导入模块
import support
 
# 现在可以调用模块里包含的函数了
support.print_func("Runoob")


*****************************************************

# test.py
import cal
print(cal.add(3,5))
# cal.py
print('cal1')
def add(x,y):
    return x + y

def sub(x,y):
    return x - y
print('cal2')

输出:

cal1
cal2
8


也可以用

from … import 语句

Python 的 from 语句让你从模块中导入一个指定的部分到当前命名空间中

from cal import add
# test.py
#import cal
from cal import add
print(add(3,5))
from cal import *
# test.py
#import cal
from cal import * # 引用所有,不推荐使用
print(add(3,5))
sys.path
# test.py
import sys
print(sys.path)     # path 是一个列表,里面是一些路径,找变量的时候就是按照里面的顺序去寻找
'''
['F:\\Python3\\module_test', # 可执行文件的路径
'F:\\Python3', 
'C:\\Users\\xiangtingshen\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 
'C:\\Users\\xiangtingshen\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', 
'C:\\Users\\xiangtingshen\\AppData\\Local\\Programs\\Python\\Python37-32\\lib', 
'C:\\Users\\xiangtingshen\\AppData\\Local\\Programs\\Python\\Python37-32', 
'C:\\Users\\xiangtingshen\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages', 
'C:\\Program Files\\JetBrains\\PyCharm 2017.3\\helpers\\pycharm_matplotlib_backend']

'''
 
 
 

猜你喜欢

转载自www.cnblogs.com/xiangtingshen/p/10430963.html