1.什么是模块
python中一个py文件就是一个模块
2.导入模块
1) import 模块名 - 在当前模块中导入指定模块,导入后可以使用指定模块中的所有声明过的全局变量
通过'模块名.全局变量'
import 模块名 as 新模块名 - 对导入的模块进行重命名
from 模块名 import 变量1,变量2,... -- 在当前模块中导入指定模块, 导入后可以使用import后的所有变量
from 模块名 import * -- 在当前模块中导入指定模块,导入后可以使用模块中的所有变量
通过'变量'
from 模块名 import 变量1 as 新变量1, 变量2 as 新变量2,...
# =============1)import直接导入============
import test1
print(test1.num)
test1.num = 200
print(test1.num)
print(test1.a)
test1.test1_func()
test1.test2_func('你好!')
# =============2)from导入==================
num = 'hello'
from test1 import num, test2_func
print(num, )
test2_func(100)
print(test1.a) # NameError: name 'test1' is not defined
from test1 import *
print(num)
print(a)
test1_func()
test2_func(100)
# ===============3) 重命名=================
# 模块重命名
import test1 as T1
print(T1.num)
print(T1.test1_func())
# 变量重命名
from test1 import num as t1_num, test1_func
print(t1_num)
test1_func()
3.导入模块的原理
1) 通过import或者from-import导入模块,本质就是去执行模块中的代码
2) 怎么阻止导入: 将需要阻止导入的代码直接或者间接放在if-main语句中
if __name__ == '__main__':
需要阻止导入的代码块
3)阻止导入的原理(了解)
每个模块都有__name__属性, 这个属性的默认值是模块的名字。
当我们直接执行模块的时候,这个模块的__name__的值就会自动变成__main__
import test1
from test1 import num
print('++++++++++++++++++')
print('module的名字:', __name__)
import test1