Python导入模块的几种方法(持续更新)

首先,一个模块就是一个文件!

常见导入模块的 3 种方式:
(1) import <模块名>
导入所有模块元素,后面用元素需要加模块前缀。

(2) from <模块名> import <代码元素>
导入模块特定元素,后面使用元素无需前缀

(3) from <模块名> import as <代码元素别名>
导入模块特定元素,并重命名元素,防止和其他模块名重名

## hello.py需要和本程序在同一个目录下,或者使用sys.path添加环境变量

import hello   # 导入hello模块中的所有代码元素
from hello import z   # 导入hello模块中的变量z
from hello import x as x2   # 导入hello模块中的变量x,并给他别名x2

x=100
y=20

print(y)
print(hello.y)  # 访问hello模块变量y
print(z)        # 访问hello模块变量z
print(x2)       # x2是hello模块x的别名

你可能感兴趣的:(Python,python,开发语言)