python 入坑路-import
一、定义
模块:用来从逻辑上组织python 代码(变量,函数,类,逻辑:实现一个功能),本质就是.py 结尾的python 文件
(文件名:test.py ,对应的模块名,test)
包:本质就是一个目录(必须带有一个__init__.py的文件)
包:用来从逻辑上组织模块。
name="keven"
def say_hello():
print("hello keven")
import module_t print(module_t.name) module_t.say_hello()
二、导入方法
import test
导入多个 以”,“ 分隔,import os,sys
当有多个方法,要导入其中一个时,from module_t import say_hello
导入所有,from module_t import * (不建议使用,会有冲突)
当这样使用时,其实是在 import 位置 把 module_t 中的代码执行一遍,如果下面有函数定义重名,就会覆盖掉模块中的
这是 import 的本质 ,针对个别函数可以取别名, from module_t import say_hello as say1
def say_hello():
pring("hello keven")
----------------------------------- 以上是module_t代码,以下是main 代码
from module_t import *
say_hello()
def say_hello():
print("in the man")
say_hello()
#输出,结果 ,如下,当 main 中定义了重名,会覆盖模板中的函数。
hello keven
in the man
导入包:import package
在 inint 文件中, from . import test #"." 从当前路径下导入test模块
相当于 在init 文件里,把.py 文件里的代码,执行一遍。
三、import 本质(路径搜索和搜索路径)
import 的本质,就是将导入的python 文件解释了一遍,传给导入的 模块名 的变量。
要调用时,module_t.name module_t.say_hello()
from module_t import say_hello ,只把 say_hello 代码执行一遍,使用时,只需要 say_hello() 就行。
两个区别:前者需要 变量名,作为媒介, 后者是直接在当前位置执行代码。
导入包的本质:就是执行包的__init__.py 文件。
需要在__init__.py文件里,import 本包下的.py 文件,
import module_t ----->module_t.py--->module_t.py的路径
导入时:模块重名,谁在路径前面,谁生效。
四、import 优化
from module_t import test ,直接从那个模块导入,避免重复寻找路径
from module_t import test as t 取别名

浙公网安备 33010602011771号