第四章 1 模块学习 ---模块的种类和导入方法

为了编写可维护的代码,我们把很多函数分组, 在python中一个.py 文件就是一个模块

好处
1 提高可维护性
2 可重用
3 避免函数名和变量名冲突

模块分为3种
1 内置标准模块(标准库) 执行help(‘modules’)查看所有python 自带模块
2 第三方模块 通过pip install模块名联网安装
3 自定义模块

#自带和从第三方下载的模块 '_'不用管主要看不带'_'的
>>> help('modules')

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

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

Enter any module name to get more help.  Or, type "modules spam" to search
for modules whose name or summary contain the string "spam".

导入模块

import module
from module import xx
from module.xx.xx import xx as rename
from module.xx.xx import *

注意:模块一旦被调用,即相当于执行了另一个py文件里的代码
举例

>>> import random    #1
>>>> random.randint(0,100)
41
>>> random.randint(0,100)
11
>>> random.randint(0,100)
7
>>>

>>> import  os  #2
>>> from os import rmdir,rename
>>>

from django.core import handers
import socket
form socket import * (不建议)

模块的导入路径

开源模块学习的安装方式
http://pypi.python.org/pypi
注册一个账号即可上传
python3 setup.py build

install

使用国内源下载模块

pip3 install -i http://pypi.douban.com/simple/paramiko --trusted-host pypi.douban.com 

包及跨模块导入1

包 package
这里写图片描述
当你的模块越来越多的时候,就需要对模块文件进行划分,比如把负责跟数据库交互的都放一个文件夹,把与页面交互相关的放一个文件夹
一个文件夹管理多个模块文件,这个文件夹就叫包
加个init.py文件就会把目录初始化成一个包
python3默认

跨模块导入2

这里写图片描述

import sys
import os
print(dir())
print(__file__)

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
print(BASE_DIR)
# print(sys.path)
# from proj import settings

def sayhi(name):
    print('hello',name)

sayhi('alex')

这里写图片描述

相对导入
文件夹被python解释器视作package需要满足一下两个条件:
1 文件夹中必须有init.py文件,该文件可以为空,但必须存在该文件
2不能作为顶层模块来执行该文件夹中的py文件(即不能作为主函数的入口)
所以这个解决办法就是,既然你在views.py里执行了相对导入,那就不要把views当作入口程序,可以通过上一级的manage.py调用views.py


from . import views
from ..proj import settings

猜你喜欢

转载自blog.csdn.net/qq_42936973/article/details/82109424