zoukankan      html  css  js  c++  java
  • python学习笔记(模块、包、标准库)

    模块

    前面有简单介绍如何使用import从外部模块获取函数并且为自己的程序所用:

    >>> import math
    >>> math.sin(0)
    0.0
    >>>

    模块是程序

    任何python程序都可以作为模块导入。假设写如下程序,并且将它保存为以F:pythonmyDemohello.py

    print 'hello,world'

    下面通过python解释器调用:

    >>> import sys
    >>> sys.path.append('F:pythonmyDemo')

    >>> import hello
    hello,world

    再导入一次:

    >>> import hello

    >>>

    怎么这次没结果?因为导入模块并不意味着在导入进执行某些操作。它们主要用于定义,比如变量、函数和类等。此外,因为只需要定义这些东西一次,导入模块多次和导入一次的效果是一样的。

    模块用于定义

    在模块中定义函数

    包含函数的简单模块(保存为hello2.py 文件):

    #hello2.py
    def hello():
    print 'hello,world!'

    模块会被执行,这意味着hello函数在模块的作用被定义了。因此可以通过以下方式来访问函数:

    >>> import hello2
    >>> hello2.hello()
    hello,world!
    >>>

    在模块中增加测试代码

     模块用来定义函数、类和其他内容,有时候在模块中添加一些检查模块本身是否正常工作的测试代码是非常有用的。 

    #hello2.py
    def hello():
    print 'hello,world!'
    def test():
    hello()

    if __name__=='__main__':test()

    ---------------------

    >>> import hello2
    >>> hello2.hello()
    hello,world!
    >>> hello2.test()
    hello,world!
    >>>

    f __name__ == '__nain__' 解释:

    python文件的后缀为.py ,.py文件可以用来直接运行,就像一个独立的小程序;也可以用来作为模块被其它程序调用。

    __name__是模块的内置属性,如果等于'__main__' 侧表示直接被使用,那么将执行方法test()方法;如果是被调用则不执行 if 判断后面的test()方法。

    文档

    模块信息的自然来源是文档,除了通过python书籍或标准python文档来查看某个函数的含义,也可以通过下面方式: 

    >>> print range.__doc__
    range(stop) -> list of integers
    range(start, stop[, step]) -> list of integers

    Return a list containing an arithmetic progression of integers.
    range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
    When step is given, it specifies the increment (or decrement).
    For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
    These are exactly the valid indices for a list of 4 elements.
    >>>

    这样就获得了关于range函数的精确描述。

    标准库

    sys

    sys模块能让你访问与Python解释器联系紧密的函数和变量

    >>> [n for n in dir(sys) if not n.startswith('_')]
    ['api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_traceback', 'exc_type', 'exc_value', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'getwindowsversion', 'hexversion', 'last_traceback', 'last_type', 'last_value', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'py3kwarning', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions', 'winver']

    os

    os模块为你提供了访问多个操作系统服务的功能

     fileinput

    fileinput模块能够遍历文本文件的所有行

    time

    time模块包含的函数能够获得当前时间,操作时间和日期,从字符串读取时间及格式化时间为字符串

    >>> dir(time)
    ['__doc__', '__name__', '__package__', 'accept2dyear', 'altzone', 'asctime', 'clock', 'ctime', 'daylight', 'gmtime', 'localtime', 'mktime', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'timezone', 'tzname']
    >>>

    help(time)之后可以知道time有2种时间表示形式:
    1、时间戳表示法,即以整型或浮点型表示的是一个以秒为单位的时间间隔。这个时间的基础值是从1970年的1月1号零点开始算起。
    2、元组格式表示法,即一种python的数据结构表示。这个元组有9个整型内容。分别表示不同的时间含义。

    (2008,1,21,21,2,56,0,21,0) #表示2008年1月21日21时2分56秒星期一,当年的第21天,无夏令时

    year (four digits, e.g. 1998)
    month (1-12)
    day (1-31)
    hours (0-23)
    minutes (0-59)
    seconds (0-59)
    weekday (0-6, Monday is 0)
    Julian day (day in the year, 1-366)
    DST (Daylight Savings Time) flag (-1, 0 or 1) ##夏令时格式,0:表示正常格式,1:表示为夏令时格式,-1:表示根据当前的日期时间格式来判定

    包含的函数:
    time() -- 返回当前时间戳,浮点数形式。不接受参数
    clock() -- 返回当前程序的cpu执行时间。unix系统始终返回全部运行时间;而windows从第二次开始都是以第一次调用此函数时的时间戳作为基准,而不是程序开始时间为基准。不接受参数。
    sleep() -- 延迟一个时间段,接受整型、浮点型。
    gmtime() -- 将时间戳转换为UTC时间元组格式。接受一个浮点型时间戳参数,其默认值为当前时间戳。
    localtime() -- 将时间戳转换为本地时间元组格式。接受一个浮点型时间戳参数,其默认值为当前时间戳。
    asctime() -- 将时间元组格式转换为字符串形式。接受一个时间元组,其默认值为localtime()返回值
    ctime() -- 将时间戳转换为字符串。接受一个时间戳,其默认值为当前时间戳。等价于asctime(localtime(seconds))
    mktime() -- 将本地时间元组转换为时间戳。接受一个时间元组,必选。
    strftime() -- 将时间元组以指定的格式转换为字符串形式。接受字符串格式化串、时间元组。时间元组为可选,默认为localtime()
    strptime() -- 将指定格式的时间字符串解析为时间元组,strftime()的逆向过程。接受字符串,时间格式2个参数,都是必选。
    tzset() -- 改变本地时区。

    例子:

    将当前时间转换为字符串格式

    >>> time.asctime()
    'Fri Aug 14 10:20:01 2015'
    >>>

    时间字符串支持的格式化符号

    格式 含义 备注
    %a 本地(locale)简化星期名称
    %A 本地完整星期名称
    %b 本地简化月份名称
    %B 本地完整月份名称
    %c 本地相应的日期和时间表示
    %d 一个月中的第几天(01 - 31)
    %H 一天中的第几个小时(24小时制,00 - 23)
    %I 第几个小时(12小时制,01 - 12)
    %j 一年中的第几天(001 - 366)
    %m 月份(01 - 12)
    %M 分钟数(00 - 59)
    %p 本地am或者pm的相应符
    %S 秒(01 - 61)
    %U 一年中的星期数。(00 - 53星期天是一个星期的开始。)第一个星期天之前的所有天数都放在第0周。
    %w 一个星期中的第几天(0 - 6,0是星期天)
    %W 和%U基本相同,不同的是%W以星期一为一个星期的开始。
    %x 本地相应日期
    %X 本地相应时间
    %y 去掉世纪的年份(00 - 99)
    %Y 完整的年份
    %Z 时区的名字(如果不存在为空字符)
    %% ‘%’字符

    random

    random模块包含返回随机数的函数,可以用于任何产生随机输出的程序

    random模块中的一些重要函数:

    下面介绍使用random模块的例子,还需要用到time模块中的函数。

    例1:首先获得代表时间间隔(2015年)限制的实数,这可以通过时间元组的方式来表示日期(使用 -1表示一周的某天,一年中某天和夏令时,以例让python自己计算),并且对这些元组调用mktime :

    from random import *
    from time import *
    date1=(2015,1,1,0,0,0,-1,-1,-1)
    time1=mktime(date1)
    date2=(2016,1,1,0,0,0,-1,-1,-1)
    time2=mktime(date2)

    random_time=uniform(time1,time2)#在这个范围内均一的生成随机数

    print asctime(localtime(random_time))#将数字转换为易读的日期形式

    ----------

    Fri Apr 03 22:56:16 2015
    >>>

    例2:下面一个例子,每次敲击回车键都为自己发一张牌,同时确保不会得到相同的牌。

    values=range(1,11)+'jack queen king'.split()#定义十三张牌
    suits='hei hong mei fang'.split() #定义牌的四种类型
    deck=['%s of %s' %(v,s) for v in values for s in suits]
    from pprint import pprint
    pprint (deck[:12])

    ---------------

    >>>
    ['1 of hei',
    '1 of hong',
    '1 of mei',
    '1 of fang',
    '2 of hei',
    '2 of hong',
    '2 of mei',
    '2 of fang',
    '3 of hei',
    '3 of hong',
    '3 of mei',
    '3 of fang']
    >>>

    随机获取

    values=range(1,11)+'jack queen king'.split()#定义十三张牌
    suits='hei hong mei fang'.split() #定义牌的四种类型
    deck=['%s of %s' %(v,s) for v in values for s in suits]
    from pprint import pprint
    from random import shuffle
    shuffle(deck)
    pprint (deck[:12])

    -------------

    ['1 of hong',
    '2 of mei',
    'queen of fang',
    '8 of mei',
    '4 of mei',
    '4 of fang',
    'king of hong',
    '2 of hei',
    '5 of fang',
    'king of fang',
    'jack of mei',
    'queen of hong']
    >>>

    按回车键发牌

    values=range(1,11)+'jack queen king'.split()#定义十三张牌
    suits='hei hong mei fang'.split() #定义牌的四种类型
    deck=['%s of %s' %(v,s) for v in values for s in suits]
    from pprint import pprint
    from random import shuffle
    shuffle(deck)
    pprint (deck[1:1])

    while deck:
    raw_input(deck.pop())

    shelve 

    >>> import shelve
    >>> s=shelve.open('test.dat')
    >>> s['x']=['a','b','c']
    >>> s['x'].append('d')
    >>> s['x']
    ['a', 'b', 'c']

    d去哪了?
    >>> temp=s['x']
    >>> temp.append('d')
    >>> s['x']=temp
    >>> s['x']
    ['a', 'b','c','d']

    简单的数据库示例

    #database.py
    import sys,shelve

    def store_person(db):
    pid =raw_input('enter unique ID number: ')
    person={}
    person['name']=raw_input('enter name: ')
    person['age']=raw_input('enter age: ')
    person['phone']=raw_input('enter phone number: ')

    db[pid]=person

    def lookup_person(db):
    pid=raw_input('enter ID number: ')
    field=raw_input('what would you like to know?(name,age,phone)')
    field=field.strip().lower()
    print field.capitalize()+':',db[pid][field]

    def print_help():
    print 'the available commands are: '
    print 'store : stores informaion about a person'
    print 'lookup :looks up a person from ID number'
    print 'quit :save changes and exit'
    print '? : prints this message'

    def enter_command():
    cmd=raw_input('enter command(? for help): ')
    cmd=cmd.strip().lower()
    return cmd

    def main():
    database=shelve.open('f:\database.dat')
    try:
    while True:
    cmd=enter_command()
    if cmd=='store':
    store_person(database)
    elif cmd=='lookup':
    lookup_person(database)
    elif cmd=='?':
    print_help()
    elif cmd=='quit':
    return
    finally:
    database.close()
    if __name__=='__main__': main()

    ------------------

    enter command(? for help):
    enter command(? for help): ?
    the available commands are:
    store : stores informaion about a person
    lookup :looks up a person from ID number
    quit :save changes and exit
    ? : prints this message
    enter command(? for help): sotre
    enter command(? for help): store
    enter unique ID number: 002
    enter name: xiao
    enter age: 22
    enter phone number: 110
    enter command(? for help): lookup
    enter ID number: 002
    what would you like to know?(name,age,phone)phone
    Phone: 110
    enter command(? for help): quit
    >>>

  • 相关阅读:
    03_ if 练习 _ little2big
    uva 11275 3D Triangles
    uva 12296 Pieces and Discs
    uvalive 3218 Find the Border
    uvalive 2797 Monster Trap
    uvalive 4992 Jungle Outpost
    uva 2218 Triathlon
    uvalive 3890 Most Distant Point from the Sea
    uvalive 4728 Squares
    uva 10256 The Great Divide
  • 原文地址:https://www.cnblogs.com/whats/p/4723601.html
Copyright © 2011-2022 走看看