Python3,我用这种方式讲解python模块,80岁的奶奶都说能理解。建议收藏 ~ ~
1、引言
小云:鱼哥,你看天上的月亮越来越圆了。
小鱼:唉~ 又是一年团圆夜,又是一年中秋节。
小云:嘿嘿,可不滴, 这个中秋,你准备分享点啥知识嘞?
小鱼:嗯??
小云:鱼哥,你这是啥表情嘛~
小鱼:我万万没想到,这么多年,你竟然…
小云:鱼哥,我这不是想多学点知识嘛 ~
小鱼:有多远你轱辘多远…
小云:嘿嘿 ~ ~ 鱼哥,你就来分享一个知识呗。
小鱼:你…说…啥…,我没听清…
小云:我说,你给我讲讲啥是python模块呗。
小鱼:你…说… 要请我吃饭??
小云:…只要你给我讲明白,那咱就去撸串。
小鱼:你早点这么大声说, 我不就开始整了嘛。
2、python模块详解
2.1 含义
什么是python模块, 就一句话:
Python 模块(Module),是一个 Python 文件,以 .py 结尾,包含了 Python 对象定义和Python语句。
换句话说:就是带.py后缀的可执行文件。
作用:用来重复调用变量和函数。
可以看这个示意图:
2.2 代码示例
我详细,写过项目的同学,都知道,如何来进行模块的封装及调用。
这里我就举个例子:
readcsv.py
# -*- coding:utf-8 -*-
# @Time : 2022-09-01
# @Author : Carl_DJ
import csv
desction = 'csv读取函数'
print(desction)
def read_csv(path):
with open(path, newline='') as csvfile:
reader = csv.DictReader(csvfile)
for i in reader:
print(i)
调用方式: 直接通过import 导入 read_csv 函数即可
代码示例
#导入rad_csv模块
from readcsv import read_csv
#文件路径
file_path = './testfile.csv'
#运行
read_csv(file_path)
这就是一个简单的调用。
这样编写的好处,就是如果需要多个地方调用,
那么只需要编辑readcsv.py文件即可, 不需要重复单独的编译多次。
2.3 进阶
想一下, 如果我们在readcsv.py 文件中,添加 if name == “main” ,有什么 作用呢?
# -*- coding:utf-8 -*-
# @Time : 2022-09-01
# @Author : Carl_DJ
import csv
desction = 'csv读取函数'
print(desction)
def read_csv(path):
with open(path, newline='') as csvfile:
reader = csv.DictReader(csvfile)
for i in reader:
print(i)
if __name__ == '__main__':
print(f'运行此脚本函数')
我们运行结果看一下:
解析:
- __main__始终指当前执行模块的名称(包含后缀.py);
- __name__是内置变量,当该模块被直接执行的时候, __name__等于文件名(包含后缀 .py )
- 如果该模块 import 到其他模块中,则该模块的 __name__等于模块名称(不包含后缀.py)
所以,
- 所以当直接执行脚本时候,name == "main"为真成立,可以继续执行后面代码;
- 而当import导入模块时候,name == "main"为假,不成立,无法执行后面代码;
3、总结
看到这里, 今天的分享差不多就结束了。
更多的python内建模块,可以通过命令来查看:
help('modules')
查询结果:
由于我安装的模块太多(含第三方模块),这里只展示一部分。
Cython charset_normalizer mailbox send2trash
IPython chunk mailcap servicemanager
MyQR ci_info main setup_cython
PIL click markupsafe setuptools
PyInstaller cmath marshal shape_infer_helper
PyPDF2 cmd math shape_optimizer
PySimpleGUI code matplotlib shelve
__future__ codecs matplotlib_inline shlex
_abc codeop mimetypes shutil
_aix_support collections mistune signal
_ast colorama mmap simplejson
_asyncio colorsys mmapfile site
_asyncio_d commctrl mmsystem six
_bisect commonmark modulefinder skimage
_blake2 compare_bert_results mouseinfo smtpd
_bootlocale compileall msgpack smtplib
_bootsubprocess concurrent msilib sndhdr
_bz2 configobj msvcrt sniffio
_bz2_d configparser multidict socket
_cffi_backend contextlib multipart socketserver
_codecs contextvars multiprocessing socks
_codecs_cn convert_longformer_to_onnx nbclient sockshandler
_codecs_hk convert_tf_models_to_pytorch nbconvert some_reportlab_snippets
_codecs_iso2022 convert_to_onnx nbformat soupsieve
_codecs_jp copy nest_asyncio spacy_pkuseg
_codecs_kr copyreg netbios spider
_codecs_tw coreapi netrc sqlite3
_collections coreschema networkx sre_compile
_collections_abc corsheaders nibabel sre_constants
_compat_pickle crispy_forms nipype sre_parse
_compression cronlog nisext srsly
_contextvars crontab nntplib ssl
_csv crontabs notebook sspi
_ctypes crypt nt sspicon
_ctypes_d css_html_js_minify ntpath starlette
_ctypes_test cssselect ntsecuritycon stat
_ctypes_test_d cssutils nturl2path statistics
_datetime csv numba storemagic
_decimal ctypes numbers string
_decimal_d curl2py numpy stringprep
_distutils_hack curses odbc struct
_elementtree cv2 onnx_exporter subprocess
_elementtree_d cycler onnx_model suit
_functools cython onnx_model_bart sunau
_hashlib cythonmagic onnx_model_bert symbol
_hashlib_d dataclasses onnx_model_bert_keras sympyprinting
_heapq datetime onnx_model_bert_tf symtable
_imp dateutil onnx_model_gpt2 sys
_io dbi onnxruntime sysconfig
_json dbm opcode tablib
_locale dde openapi_codec tabnanny
_lsprof debugpy openpyxl tarfile
_lzma decimal operator telnetlib
_lzma_d decorator operator_type_usage_processors tempfile
_markupbase defusedxml optimizer tenacity
_md5 diff_match_patch optparse termcolor
_msi difflib ordlookup terminado
_msi_d dis orjson test
_multibytecodec distutils ort_flatbuffers_py testpath
_multiprocessing django ort_model_processor tests
_multiprocessing_d doctest os textwrap
_opcode docutils packaging this
_operator docx pandas threading
_osx_support docxcompose pandocfilters tifffile
_overlapped docxtpl parity_check_helper time
_overlapped_d dot_parser parser timeit
_peg_parser email parso timer
_pickle encodings past tkinter
_py_abc encutils pathlib token
_pydecimal ensurepip pdb tokenize
_pydev_bundle entrypoints pdfkit tornado
_pydev_comm enum pefile tqdm
_pydev_imps errno pendulum trace
_pydev_runfiles et_xmlfile perfmon traceback
_pydevd_bundle etelemetry peutils tracemalloc
_pydevd_frame_eval fastapi pickle traitlets
_pyinstaller_hooks_contrib faulthandler pickleshare traits
_pyio ffmpy pickletools treedir
_pyrsistent_version ffmpy3 pikepdf tty
_queue filecmp pip turtle
_queue_d filediff pipes turtledemo
_random fileinput pkg_resources types
_sha1 filelock pkgutil typing
_sha256 filetype platform typing_extensions
_sha3 fire playwright unicodedata
_sha512 fitz plistlib unicodedata_d
_shaded_ply flask poplib unittest
_shaded_thriftpy flatbuffers posixpath uritemplate
_signal float16 pprint url_normalize
_sitebuiltins fnmatch premailer urllib
_socket formatter profile urllib3
_socket_d formtools profiler utils
_sqlite3 fractions prometheus_client uu
_sqlite3_d frontend prompt_toolkit uuid
_sre frozenlist prov uvicorn
_ssl ftplib pstats uwsgiconf
_ssl_d functools pty uwsgify
_stat fusion_attention pvectorc validate
_statistics fusion_base py2exe venv
_string fusion_biasgelu pyPdf warnings
_strptime fusion_embedlayer py_compile watchdog
_struct fusion_fastgelu pyautogui watermarker
_symtable fusion_gelu pyclbr wave
_testbuffer fusion_gelu_approximation pycompletionserver wcwidth
_testbuffer_d fusion_gpt_attention pycparser weakref
_testcapi fusion_gpt_attention_megatron pydantic webbrowser
_testcapi_d fusion_gpt_attention_no_past pydev_app_engine_debug_startup webencodings
_testconsole fusion_layernorm pydev_console websockets
_testconsole_d fusion_options pydev_coverage werkzeug
_testimportmultiple fusion_reshape pydev_ipython wheel
_testimportmultiple_d fusion_shape pydev_pysrc widgetsnbextension
_testinternalcapi fusion_skiplayernorm pydev_test_pydevd_reload win2kras
_testinternalcapi_d fusion_utils pydev_tests win32_setctime
_testmultiphase future pydev_tests_mainloop win32api
_testmultiphase_d gc pydev_tests_python win32clipboard
_thread gdown pydevconsole win32com
_threading_local generate_test_data pydevd win32con
_tkinter genericpath pydevd_concurrency_analyser win32console
_tkinter_d getopt pydevd_file_utils win32cred
_tracemalloc getpass pydevd_plugins win32crypt
_uuid gettext pydevd_pycharm win32cryptcon
_uuid_d gevent pydevd_tracing win32ctypes
_version glob pydoc win32event
_virtualenv gpt2_beamsearch_helper pydoc_data win32evtlog
_warnings gpt2_beamsearch_tester pydot win32evtlogutil
_weakref gpt2_helper pyee win32file
_weakrefset gpt2_parity pyexpat win32gui
_win32sysloader gpt2_tester pyexpat_d win32gui_struct
_winapi graphlib pyforest win32help
_winxptheme greenlet pygetwindow win32inet
_xxsubinterpreters gridfs pygments win32inetcon
_yaml gzip pylab win32job
_zoneinfo h11 pymatting win32lz
_zoneinfo_d hashlib pymongo win32net
bert_perf_test jsonschema reprlib wkhtmltopdf
bert_test_data jupyter requests wsgiref
binascii jupyter_client requests_cache xdrlib
binhex jupyter_core requests_cache_mongodb xlrd
bisect jupyterlab_pygments rest_framework xlsxwriter
bleach jupyterlab_widgets rest_framework_swagger xlwings
bs4 keyword retcode xml
bson kiwisolver retrying xmlrpc
builtins lib reversion xxsubtype
bz2 lib2to3 rich yaml
cProfile libfuturize rlcompleter yarl
cachetools libpasteurize rmagic zhdate
calendar linecache runfiles zipapp
catalogue llvmlite runpy zipextimporter
cattr locale sched zipfile
cattrs logging scipy zipfile36
cchardet loguru scripts zipimport
certifi longformer secrets zlib
cffi longformer_helper select zmq
cgi lxml select_d zoneinfo
cgitb lzma selectors
chardet machine_info selenium
当然了,如果想看内建函数,也可以直接点击跳转:
- 《Python3,这应该是,使用最广泛的6个内置函数,别说你还不知道。》
- 《Python3,不知道Python内置库函数,不要错过这篇,必须收藏!!》
我是小鱼:
- CSDN 博客专家;
- 阿里云 专家博主;
- 51CTO 博客专家;
- 51认证讲师;
- 金牌面试官&面试培训师;
关注我,带你学习更多更有趣的Python知识。
- 点赞
- 收藏
- 关注作者
评论(0)