跟老齐学Python之Import 模块
认识模块
对于模块,在前面的一些举例中,已经涉及到了,比如曾经有过:import random (获取随机数模块)。为了能够对模块有一个清晰的了解,首先要看看什么模块,这里选取官方文档中对它的定义:
A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module's name (as a string) is available as the value of the global variable name.
都是洋码子,翻译一下不?不!还是只说要点:
•模块就是一个含有python语句的文件
•模块名就是文件名(不要扩展名.py)
那么,那个import random的文件在哪里呢?
用曾经讲过的那个法宝:help()函数看看:
>>> help(random)
然后就出现:
NAME
random - Random variable generators.
FILE
/usr/local/lib/python2.7/random.py
MODULE DOCS
http://docs.python.org/library/random
DESCRIPTION
...
这里非常明显的告诉我们,random模块的文件就是: /usr/local/lib/python2.7/random.py(注意:这个地址是我的计算机中的地址,可能跟看官的不一样,特别是如果看官用的是windows,肯定跟我这个不一样了。)
看官这时候可能有疑问了,import是怎么找到那个文件的?类似文件怎么写?不用着急,这些我都会一一道来。
标准库
看了前面的random这个例子,看官可能立刻想到一个问题:是不是已经有人把很多常用的功能都写成模块了?然后使用者只需要用类似方法调用即可。的确是,比如上面显示的,就不是某个程序员在使用的时候自己编写的,而是在安装python的时候,就被安装在了计算机里面。观察那个文件存储地址,就知道了。
我根据上面得到的地址,列出/usr/local/lib/python2.7/里面的文件,这些文件就是类似random的模块,由于是python安装就有的,算是标配吧,给它们一个名字“标准模块库”,简称“标准库”。
这张图列出了很少一部分存在这个目录中的模块文件。
Python的标准库(standard library)是Python的一个组成部分,也是Python为的利器,可以让编程事半功倍。
如果看官有时间,请经常访问:https://docs.python.org/2/library/,这里列出了所有标准库的使用方法。
有一点,请看官特别注意,对于标准库而言,由于内容太多,恐怕是记不住的。也不用可以的去记忆,只需要知道有这么一个东西。如果在编写程序的时候,一定要想到,对于某个东西,是不是会有标准库支持呢?然后就到google或者上面给出的地址上搜索。
举例:
>>> import sys #导入了标准库sys
>>> dir(sys) #如果不到网页上看,用这种方法可以查看这个标准库提供的各种方法(函数)
['__displayhook__', '__doc__', '__egginsert', '__excepthook__', '__name__', '__package__', '__plen', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', '_mercurial', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'hexversion', 'last_traceback', 'last_type', 'last_value', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'py3kwarning', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions']
>>> sys.platform #比如这个
'linux2'
>>> sys.version #还有这个
'2.7.6 (default, Nov 13 2013, 19:24:16) \n[GCC 4.6.3]'
>>> help(sys.stdin) #这是查看某个模块方法具体内容的方式
标准库,在编程中经常用到。这里不赘述。只要看官能够知道在哪里找、如何找所需要的标准库即可。
自己编写模块
- 上一篇:跟老齐学Python之传说中的函数编写条规
- 下一篇:跟老齐学Python之类的细节