Python 基础 - Day 5 Learning Note - 模块 之 介绍篇

定义


模块(module)支持从逻辑上组织Python代码,本质就是.py结尾的python文件(e.g.文件名:test.py; 模块名:test),目的是实现某项功能。将其他模块属性附加到你的模块中的操作叫导入(import)。

模块分为三类:标准库、开源模块(open source module)和自定义模块。

包(package)是一个有层次的文件目录结构, 定义了一个由模块和子包组成的python应用程序执行环境。和模块及类一样,也使用句点属性标识来访问他们的元素。使用标准的import和from-import语句导入。

导入模块


导入常用语法

模块导入本质就是一个路径搜索的过程。 即在文件系统“预定义区域”查找你所需要的模块文件。 预定义区域是python搜索路径的集合 - 列表。

# 方法一
import mudule_name  #导入整个模块,载入时执行

import module_name as MA   # 扩张 as 

# 方法二
from module_name import name1   # 导入指定模块属性

from module_name import name1 as n1 # 扩张 as  

#特别注意fe
from . import test1  # 相对导入,自当前目录导入test1

from module_name import*   # 不建议使用,非良好编程风格,很可能覆盖当前名称空间中现有的名字。
#!usr/bin/envpython
#-*-coding:utf-8-*-

importsys,os

print(sys.path)#返回为列表,包含模块库的路径

x=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(x)#将指定含有自定义的模块存入模块库路径列表中
将自定义模块添加到路径搜索区域中

import语句和from-import语句的区别

在import语句下,调用模块属性 需要 使用属性/句点属性标识 (如 module_name.logger() 或 os.path.abspath())的方式。 import语句的本质是将 模块中所有的代码 赋值给 模块名

而from-import语句是 copy了模块中指定属性的代码并在当前文件下执行。所以,在from-import语句下,不需要用句点属性标识,直接可以调用函数或者类 (logger())。 在效率上,由于运行方式的不同, from-import语句比import语句的速度更快。

标准库的分类


标准库就其大致用途可分为四类:data persistence and exchange, in-memory data structure, file access, and text process tools。以下是python module of the week 的详细分类

 Categories Module name  Brief 
Built-in objects exceptions  built-in error classes (自动导入)
String service      codes  string encoding and decoding
 difflib working with text
 String IO and cStringIO work with text buffers using file-like API (read, write. etc.)
 re regular expression
 struct working with Binary Data 
 textwrap formatting text paragraphs 
Data type           array sequence of fixed-type data
 datetime date/time value manupulation
 calendar work with dates
 collections container data types
 heapq in-place heap sort algorithm
 bisect maintain lists in sorted order
 schedgeneric event scheduler
 Queuea thread-safe FIFO implementation (comparied with built-in function such as pop() and insert())
 weakrefgarbage-collectable references to objects 
 copyduplicate objects  
 pprintpretty-print data structure 
Numeric & mathematical module       decimalfixed and floating point math 
 fractionsrational numbers 
 functoolstoos for manipultaing functions 
 itertoolsiterator functions for efficient looping 
 mathmathematical function 
 operatorfunctional interface to built-in operators 
 randompseudorandom number generator  
Internet data handling    base64encode binary data into ASCII characters 
 jsonJavaScript Object Notation Serializer 
 mailboxaccess and manipulate emial achives 
 mhlibwork with MH mailboxes 
File formats    cvs comma-separated value files 
 ConfigParserwork with configuration files
 robotparserinternet spider access control 
Cryptographic services   hashlibcryptographic hashes and messary digests  
 hmaccryptographic signature and verification of messages 
File and Directory access          os.path platform-independent manipulation of file names 
 fileinput process lines from input streams 
 filecmp compare files 
 tempfilecreate temporary filesystem resources 
 globfilename pattern matching 
 fnmatchcompare filenames against Unix-style glob partterns 
 linecacheread text files efficiently 
 shutilhigh-level file opeerations 
 dircachecache directory listings 
Data compression and archiving      bz2bzip2 compression 
 gzipread and write GNU zip files 
 tarfiletar archive access 
 zipfileread and write ZIP archive files 
 zliblow-level access to GNUzlib compression library 
Data persistence    anydbmaccess to DBM-style database
 dbhashDBM-style API for the BSD database library
 dbmsimple database interface 
 dumbdbmportable DBM implementation
 gdbmGNU's version of the dbm library
 pickle and cPicklepython object serialization 
 shelvepersistent storage of arbitrary Python objects
 whichdbidentify DBM-style database formats
 sqlite3embedded relational database
Generic operating system service   osportable access to operating system specific features
 timefunctions for manipulating clock time 
 getoptcommand line option parsing
 optparsecommand line option parser to replace getopt
 argparsecommand line option and argument parsing  
 loggingreport status, error, and informational messages
 getpassprompt the user for a password without echoing
 platformaccess system version information
Optional operating system services  threadingmanage concurrent threads
 mmapmemory-map files
 multiprocessing manage processes like threads 
 readlineinterface to the GNU readline library
 rlcompleteradds tab-completion to the interactive interpreter
Unix-specific services commandsrun external shell commands
 grpUnix group database
 pipesUnix shell command pipeline templates
 pwdUnix password database
 resourcesystem resource management 
Interprocess communication and networking asynchat asynchronous protocol handler
 asyncoreasynchronous I/O handler
 signalreceive notification of asynchronous system events
 subprocesswork with additional processes

Internet protocols and support

网络协议及支持

 BaseHTTPServerbase classes for implementing web servers
 cgitbdetailed traceback reports
 CookiesHTTP Cookies
 imaplibIMAP4 client library
 SimpleXMLRPCServerimplemens an XML-RPC server
 smtpdSample SMTP Servers
 smtplibSimple Mail Transfer Protocol client
 socketNetwork Communication
 select wait for I/O Efficiently
 SocketServerCreating network servers
 urllibsimple interface for network reserouce access
 urllib2Library for opening URLs
 urlparsesplit URL into component pieces
 uuiduniversally unique identifiers
 webbrowserDisplays web pages
 xmlrpclibclient-side liabrary for XML-RPC communication 
Structured markup processing tools xml.etree.ElementTreeXML manipulation API

Internationalization

国际化

 gettextMessage Catalogs
 localePOSIX cultural localization API

Program frameworks

程序框架

 cmdcreate line-oriented command processes
 shlexlexical analysis of shell-style syntaxes

Development Tools

开发工具

 doctestTesting through documentation
 pydocOnline help for python modules
 unittestAutomated testing framework
 pdbInterative Debugger
Debugging and Profiling profile, cProfile, and pstats Performance analysis of Python programs
 timeitTime the execution of samll bits of Python code
 traceFollow Python statements as they are executed 
Python Runtime Services abc Abstract Base Classes
 atexitCall functions when a program is closing down 
 contextlibcontext manager utilities
 gcGarbage Collector
 inspectInspect live objects
 siteSite-wide configuration
 sysSystem-specific Configuration
 sysconfigInterpreter Compile-time Configuration
 tracebackExtract, format, and print exceptions and stack traces
 warningsNon-fatal alerts
Python Language Services compileallByte-compile Source Files 
  disPython Bytecode Disassembler
  pyclbrPython class browser support
  tabnannyIndentation validator
Importing Modules impInterfact to module import mechanism
  pkclbrPackage Utilities
  zipimportLoad Python code from inside ZIP archives
Miscelaneous EasyDialogs Carbon dialogs for Mac OS X
  plistlibManipulate OS X property list files

 Source: python module of the week,  Douh Hellmann

 

Reference

http://www.cnblogs.com/wupeiqi/articles/4963027.html

http://www.cnblogs.com/alex3714/articles/5161349.html

module of the week, 全部标准库模块的释义,非常有用。

 

转载于:https://www.cnblogs.com/lg100lg100/p/7346265.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值