Python全栈之路----常用模块学习----模块的种类和导入方法

什么是模块?

        在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,越来越不容易维护。

        为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,这样,每个文件包含的代码就相对较少,很多编程语言都采用这种组织代码的方式。在Python里,一个 .py 文件就被称之为一个模块(Module)。

使用模块有什么好处?

       1.最大的好处是大大提高了代码的可维护性。其次,编写代码不必从零开始。带一个模块编写完毕,就可以被其他地方引用。我们在编写程序的时候,也经常引用其他模块,包括Python内置的模块和来自第三方的模块。

       2.使用模块还可以避免函数名和变量名冲突。每个模块有独立的命名空间,因此相同名字的函数和变量完全可以分别存在不同的模块中,所以,我们自己在编写模块时,不必考虑名字会与其他模块冲突。

模块分类

模块分为三类:

  • 内置标准模块(又称标准库)执行 help('models') 查看所有 python 自带模块列表
>>> help('modules')

Please wait a moment while I gather a list of all available modules...

__future__          _tkinter            gettext             sched
_abc                _tracemalloc        glob                secrets
_ast                _warnings           gzip                select
_asyncio            _weakref            hashlib             selectors
_bisect             _weakrefset         heapq               setuptools
_blake2             _winapi             hmac                shelve
_bootlocale         abc                 html                shlex
_bz2                aifc                http                shutil
_codecs             antigravity         idlelib             signal
_codecs_cn          argparse            imaplib             site
_codecs_hk          array               imghdr              smtpd
_codecs_iso2022     ast                 imp                 smtplib
_codecs_jp          asynchat            importlib           sndhdr
_codecs_kr          asyncio             inspect             socket
_codecs_tw          asyncore            io                  socketserver
_collections        atexit              ipaddress           sqlite3
_collections_abc    audioop             itertools           sre_compile
_compat_pickle      base64              json                sre_constants
_compression        bdb                 keyword             sre_parse
_contextvars        binascii            lib2to3             ssl
_csv                binhex              linecache           stat
_ctypes             bisect              locale              statistics
_ctypes_test        builtins            logging             string
_datetime           bz2                 lzma                stringprep
_decimal            cProfile            macpath             struct
_distutils_findvs   calendar            mailbox             subprocess
_dummy_thread       cgi                 mailcap             sunau
_elementtree        cgitb               marshal             symbol
_functools          chunk               math                symtable
_hashlib            cmath               mimetypes           sys
_heapq              cmd                 mmap                sysconfig
_imp                code                modulefinder        tabnanny
_io                 codecs              msilib              tarfile
_json               codeop              msvcrt              telnetlib
_locale             collections         multiprocessing     tempfile
_lsprof             colorsys            netrc               test
_lzma               compileall          nntplib             textwrap
_markupbase         concurrent          nt                  this
_md5                configparser        ntpath              threading
_msi                contextlib          nturl2path          time
_multibytecodec     contextvars         numbers             timeit
_multiprocessing    copy                opcode              tkinter
_opcode             copyreg             operator            token
_operator           crypt               optparse            tokenize
_osx_support        csv                 os                  trace
_overlapped         ctypes              parser              traceback
_pickle             curses              pathlib             tracemalloc
_py_abc             dataclasses         pdb                 tty
_pydecimal          datetime            pickle              turtle
_pyio               dbm                 pickletools         turtledemo
_queue              decimal             pip                 types
_random             difflib             pipes               typing
_sha1               dis                 pkg_resources       unicodedata
_sha256             distutils           pkgutil             unittest
_sha3               doctest             platform            urllib
_sha512             dummy_threading     plistlib            uu
_signal             easy_install        poplib              uuid
_sitebuiltins       email               posixpath           venv
_socket             encodings           pprint              warnings
_sqlite3            ensurepip           profile             wave
_sre                enum                pstats              weakref
_ssl                errno               pty                 webbrowser
_stat               faulthandler        py_compile          winreg
_string             filecmp             pyclbr              winsound
_strptime           fileinput           pydoc               wsgiref
_struct             fnmatch             pydoc_data          xdrlib
_symtable           formatter           pyexpat             xml
_testbuffer         fractions           queue               xmlrpc
_testcapi           ftplib              quopri              xxsubtype
_testconsole        functools           random              zipapp
_testimportmultiple gc                  re                  zipfile
_testmultiphase     genericpath         reprlib             zipimport
_thread             getopt              rlcompleter         zlib
_threading_local    getpass             runpy

Enter any module name to get more help.  Or, type "modules spam" to search
for modules whose name or summary contain the string "spam".
  • 第三方开源模块,可通过 pip install 模块名 联网安装
  • 自定义模块

模块调用

import module
from module import xx
from module.xx.xx import xx as rename  #有的模块名太长,就重新命名一下,用起来方便
from module.xx.xx import *  #将module.xx.xx里的所有模块全部引入,但不推荐,变量名易重复出问题

注意:模块一旦被调用,

猜你喜欢

转载自www.cnblogs.com/Moxiaoyu666/p/10415686.html