一、自定义模块
- 自定义模块一般是在项目中根据自己的需求进行的封装
- 项目中自定义了一个模块,module.py
name = "张三"
age = 23
weight = 160
height = 187
def test():
print("测试的方法")
def demo():
print("天使的眼泪")
def fn():
print("老鼠爱大米")
二、自定义模块使用
- 通过import的方式导入自定义模块module
import module
# 访问module模块中的变量
print(module.name)
print(module.age)
print(module.weight)
print(module.height)
# 调用module模块中的函数
module.test()
module.demo()
module.fn()
- 通过from…import… 导入module模块中常见的变量和函数
from module import * # *表明通配符,代表模块中的所有内容
print(name)
print(age)
print(weight)
print(height)
test()
demo()
fn()
- 通过from 模块名 import 模块中的变量或函数(准确导入)
from module import name,age,demo,fn
print(name)
print(age)
demo()
fn()
三、第三方模块
- 一般是别人解决特定问题的功能进行了封装,可以通过安装直接使用
- 注意
- 第三方模块需要先安装,才能使用
- 常见的安装方式:通过pip工具或者通过pycharm编辑器进行安装
四、pip指令安装
pip -V # 查看pip的版本 pip 23.2.1 from D:Python312Libsite-packagespip (python 3.12)
pip list # 表明查看当前缓存中安装的所有扩展
python.exe -m pip install --upgrade pip # 表明更新pip版本 Successfully installed pip-23.3.2
pip install 要安装的模块名 # 若未指定安装模块的版本,默认安装的是最新的版本
pip install 模块名 -i https://pypi.douban.com/simple/ # 设置临时国内镜像
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/ # 设置永久镜像
pip uninstall 模块名 # 表明卸载指定的模块
五、练习
- 使用pip安装numpy、pandas、matplotlib、requests
pip install numpy # 安装numpy
pip install pandas -i https://pypi.douban.com/simple/ # 使用国内镜像安装pandas
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/ # 设置阿里云为永久镜像 Writing to C:Users49269AppDataRoamingpippip.ini
pip install matplotlib # Successfully installed contourpy-1.2.0 cycler-0.12.1 fonttools-4.47.0 kiwisolver-1.4.5 matplotlib-3.8.2 packaging-23.2 pillow-10.1.0 pyparsing-3.1.1
pip install requests # Successfully installed certifi-2023.11.17 charset-normalizer-3.3.2 idna-3.6 requests-2.31.0 urllib3-2.1.0
pip uninstall numpy # 卸载numpy Successfully uninstalled numpy-1.26.2
pip uninstall pandas # 卸载pandas
六、pycharm编辑器进行安装
- File > Settings > Project > Python Interperter,通过加号进行安装扩展,减号进行卸载扩展
七、使用安装的第三方模块
# 导入pandas模块
import pandas
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...