您的位置:首页 > 编程语言 > Python开发

python模块

2016-07-27 22:14 435 查看
模块在物理上表现为以.py结尾的代码文件

一个文件别看做一个独立的模块,一个模块也可以被看做是一个文件

模块的文件名就是模块的名字加上扩展名.py

每个模块都有自己的名字空间

python允许导入其他模块以实现代码重用,从而实现了将独立的代码文件组织成更大的程序系统

python中,模块也是对象

在一个模块的顶层定义的所有变量都在被导入时成为了被导入模块的属性

一个python程序通常包括一个顶层文件和其他的模块文件

顶层文件:包含了程序的主要控制流

模块文件:为顶层文件或其他模块提供各种功能性组件

模块首次导入时(或重载),python会立即执行模块文件的顶层程序代码(不在函数体内)

导入模块:

import module1[,module2…..]

导入指定模块的部分属性

from module import name1[,name2….]

import 和from import 是可执行语句,类似于def,因此可以嵌套在if测试中,出现在def中

import 和from import 都是隐性赋值语句

import将整个模块对象赋值给一个变量名

from将一个或多个变量名赋值给导入此模块的模块中的同名对象

模块就是名称空间

模块的名称空间可以通过属性

列出所有模块

import导入指定的模块时会执行三个步骤:

找到模块文件,程序的主目录,pythonpath目录,标准链接库目录,任何.pth文件的内容

编译成字节码

执行模块的代码来创建所定义的对象

模块只有在第一次导入时才会执行

reload()用于重新加载模块

In [1]: help('modules')

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

ANSI                aptsources          htmlentitydefs      sets
BaseHTTPServer      argparse            htmllib             setuptools
Bastion             array               httplib             sgmllib
CDROM               ast                 ihooks              sha
CGIHTTPServer       asynchat            imaplib             shelve
Canvas              asyncore            imghdr              shlex
ConfigParser        atexit              imp                 shutil
Cookie              audiodev            importlib           signal
DLFCN               audioop             imputil             simplegeneric
Dialog              autoreload          inspect             site
DocXMLRPCServer     axi                 io                  sitecustomize
FSM                 base64              itertools           six
FileDialog          bdb                 json                smtpd
FixTk               binascii            keyword             smtplib
HTMLParser          binhex              lib2to3             sndhdr
IN                  bisect              linecache           socket
IPython             bs4                 linuxaudiodev       spwd
MimeWriter          bsddb               locale              sqlite3
MySQLdb             bz2                 logging             sre
Queue               cPickle             lsb_release         sre_compile
ScrolledText        cProfile            macpath             sre_constants
SimpleDialog        cStringIO           macurl2path         sre_parse
SimpleHTTPServer    calendar            mailbox             ssl
SimpleXMLRPCServer  cgi                 mailcap             stat
SocketServer        cgitb               markupbase          statvfs
StringIO            chardet             marshal             storemagic
TYPES               chunk               math                string
Tix                 cmath               md5                 stringold
Tkconstants         cmd                 mhlib               stringprep
Tkdnd               code                mimetools           strop
Tkinter             codecs              mimetypes           struct
UserDict            codeop              mimify              subprocess
UserList            collections         mmap                sunau
UserString          colorama            modulefinder        sunaudio
_LWPCookieJar       colorsys            multifile           svg_regex
_MozillaCookieJar   command             multiprocessing     svg_transform
__builtin__         commands            mutex               symbol
__future__          compileall          netrc               sympyprinting
_abcoll             compiler            new                 symtable
_ast                contextlib          nis                 sys
_bisect             contrib             nntplib             sysconfig
_bsddb              cookielib           ntpath              syslog
_codecs             copy                nturl2path          tabnanny
_codecs_cn          copy_reg            numbers             tarfile
_codecs_hk          crypt               octavemagic         telnetlib
_codecs_iso2022     csv                 opcode              tempfile
_codecs_jp          ctypes              operator            termios
_codecs_kr          curses              optparse            test
_codecs_tw          cythonmagic         os                  tests
_collections        datetime            os2emxpath          textwrap
_csv                dbhash              ossaudiodev         this
_ctypes             dbm                 packages            thread
_ctypes_test        deb822              parallelmagic       threading
_curses             debconf             parser              time
_curses_panel       debian              pdb                 timeit
_elementtree        debian_bundle       pexpect             tkColorChooser
_functools          decimal             pickle              tkCommonDialog
_hashlib            decorator           pickletools         tkFileDialog
_heapq              difflib             pip                 tkFont
_hotshot            dircache            pipes               tkMessageBox
_io                 dis                 pkg_resources       tkSimpleDialog
_json               distlib             pkgutil             toaiff
_locale             distutils           platform            token
_lsprof             doctest             plistlib            tokenize
_markerlib          dumbdbm             popen2              trace
_md5                dummy_thread        poplib              traceback
_multibytecodec     dummy_threading     posix               ttk
_multiprocessing    easy_install        posixfile           tty
_mysql              email               posixpath           turtle
_mysql_exceptions   encodings           pprint              types
_osx_support        errno               profile             unicodedata
_pyio               exceptions          pstats              unittest
_random             fcntl               pty                 urllib
_sha                fdpexpect           pwd                 urllib2
_sha256             filecmp             pxssh               urllib3
_sha512             fileinput           py_compile          urlparse
_socket             fnmatch             pyclbr              user
_sqlite3            formatter           pydoc               uu
_sre                fpectl              pydoc_data          uuid
_ssl                fpformat            pyexpat             warnings
_strptime           fractions           quopri              wave
_struct             ftplib              random              weakref
_symtable           functools           re                  webbrowser
_sysconfigdata      future_builtins     readline            wheel
_sysconfigdata_nd   gc                  repr                whichdb
_testcapi           genericpath         requests            wsgiref
_threading_local    getopt              resource            xapian
_warnings           getpass             rexec               xdrlib
_weakref            gettext             rfc822              xml
_weakrefset         glob                rlcompleter         xmllib
abc                 grp                 rmagic              xmlrpclib
aifc                gzip                robotparser         xxsubtype
antigravity         hashlib             runpy               yocto_css
anydbm              heapq               sched               zipfile
apt                 hmac                scour               zipimport
apt_inst            hotshot             screen              zlib
apt_pkg             html5lib            select
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: