python 导入模块、变量、函数、类 的几种方式 | 您所在的位置:网站首页 › python导入模块的方法有 › python 导入模块、变量、函数、类 的几种方式 |
文章目录
一、导入模块、函数/类 的方式1.1、import 模块名1.2、import 模块1,模块2, ... 模块N:导入多个模块名1.3、from 模块名 import 函数名 N :导入并指定函数1.4、from 模块名 import `*` :导入所有函数(不推荐)1.5、as :为导入模块、变量或函数 起 别名1.5.1、为 模块 起别名:1.5.2、为 变量/函数/类 起别名:
二、总结三、import 本质是路径搜索(默认优先级:可以修改)
一、导入模块、函数/类 的方式
1.1、import 模块名
语法: import 模块名示例: 定义 helloworld.py ,内容: def say_hello(): print('hello') def say_world(): print('world')test.py ,内容: import helloworld # 引入模块 helloworld.say_hello()执行结果: hello 1.2、import 模块1,模块2, … 模块N:导入多个模块名方法1: import 模块1 import 模块2 .... import 模块N方法2: import 模块1 [,模块2,... ,模块N] 1.3、from 模块名 import 函数名 N :导入并指定函数如果只导入模块中的某个变量,函数名,使用下面的方式。 语法: from 模块名 import 函数名1[,函数名2,...]示例: 新建 test2.py 文件,内容: from helloworld import say_hello say_hello()执行结果: hello 1.4、from 模块名 import * :导入所有函数(不推荐)语法: from 模块名 import *示例: 新建 test4.py 文件,内容: from helloworld import * say_hello() say_world()运行结果: hello world 1.5、as :为导入模块、变量或函数 起 别名起别名 有两个好处: 简化 模块名、函数/类的名称如果模块名、函数/类的名称相同时,后面的会将前面的覆盖掉。 1.5.1、为 模块 起别名: import 模块名 as 模块的别名示例1: 新建 test7.py 文件,内容: import helloworld as h h.say_hello() h.say_world()运行结果: hello world 1.5.2、为 变量/函数/类 起别名: from 模块名 import 函数/类 as 函数的别名示例2: 新建 test8.py 文件,内容: from helloworld import say_hello as hello hello()运行结果: hello 二、总结 import moduleA # 导入模块 import moduleA, moduleB # 导入多个模块 from mouduleA import say_hello # 导入模块的指定函数或类 from mouduleA import * # 导入模块所有的功能。(不建议使用)等同复制所有功能过来 from mouduleA as xx # 导入模块,并为模块起别名 from mouduleA import say_hello as hello # 导入模块中指定的函数,并为函数起别名 三、import 本质是路径搜索(默认优先级:可以修改)1、导入模块,首先找寻相同目录下是否有该模块, 2、如果没有找到继续找sys定义的搜索路径变量, 3、如果所有的路径都找不到该模块,就报错。 举列说明: sys: 变量定义的搜索路径命令。 import sys,os print(sys.path) sys.path.append(目录绝对路径)我们可以把新的路径加入到 sys 定义的环境变量,这样就多出一条路径可以搜索 。 导入包的本质: 执行该包里面的 __init__.py 文件 import package_test # 等于执行了 package_test 目录下的__init__.py该文件 |
CopyRight 2018-2019 实验室设备网 版权所有 |