无标题文章

2016-09-26  本文已影响0人  interjose

Head_First_Python-函数模块

BIF

for num in range():
    print(num)

drugstore

模块的建立与储存

  1. 建立好.py源程序
  2. 为模块创建一个文件夹,将.py源程序放入
  3. 在新文件夹中建立一个setup.py的文件并编辑这个文件
from distutils.core import setup
setup(
    name ='print_lol',%参数可自行调整
    version ='1.0.0',
    py_modules ='print_lol'],
    author ='interjose',
    author_email ='shenjiemin@outlook.com',
    description ='A simple printer of lists',
    )
  1. 构建发布
    • 打开cmd
    • 输入 C:\Users\Administrator>cd C:\Users\Administrator\Desktop\print_lol %找到新建立的文件夹的路径,%路径根据自己设置调整
    • 输入 C:\Users\Administrator\Desktop\print_lol>"D:\Program Files\python\python.exe" setup.py sdist
    • 输入 C:\Users\Administrator\Desktop\print_lol>"D:\Program Files\python\python.exe" setup.py install
    • 需要使用模块时通过import模块调用 %为防止模块名冲突,常通过 文件夹名.模块名()调用,通过模块实现命名空间

额外的参数控制

原函数

movies = ["The Holy Grail",1975,"Terry Jones & Terry Gilliam",91,["Graham Chapman",["Michael Palin","John Cleese","Terry Gilliam","Eric Idle","Terry Jones"]]]
>>> def print_lol(the_list):%定义一个print_lol的函数
    for each_item in the_list:
        if isinstance(each_item,list):
            print_lol(each_item)%如果为真则对这个列表元素执行print_lol函数
        else:
            print(each_item)%打印列表元素

>>> print_lol(movies)
The Holy Grail
1975
Terry Jones & Terry Gilliam
91
Graham Chapman
Michael Palin
John Cleese
Terry Gilliam
Eric Idle
Terry Jones

新要求:发现一个嵌套列表时,就让它缩进

>>> def print_lol(the_list,level):%参数the_list,level
    for each_item in the_list:
        if isinstance(each_item,list):
            print_lol(each_item,level+1)%重点level+1,每一次递归的过程中增加一个TAB。递归调用函数一定要注意函数参数的个数问题。
        else:
            for tap_stop in range(level):%控制TAB的个数
                print("\t",end='')      % "\t",end=''TAB
            print(each_item)
>>> print_lol(movies,0)
The Holy Grail
1975
Terry Jones & Terry Gilliam
91
    Graham Chapman
        Michael Palin
        John Cleese
        Terry Gilliam
        Eric Idle
        Terry Jones

新要求:提供可选参数,并通过可选参数控制是否需要缩进

>>> def print_lol(the_list,indent=False,level=0):
    for each_item in the_list:
        if isinstance(each_item,list):
            print_lol(each_item,indent,level+1)
        else:
            if indent:
                for tap_stop in range(level):
                    print("\t",end='')
            print(each_item)
>>> print_lol(movies)
The Holy Grail
1975
Terry Jones & Terry Gilliam
91
Graham Chapman
Michael Palin
John Cleese
Terry Gilliam
Eric Idle
Terry Jones
>>> print_lol(movies,True)
The Holy Grail
1975
Terry Jones & Terry Gilliam
91
    Graham Chapman
        Michael Palin
        John Cleese
        Terry Gilliam
        Eric Idle
        Terry Jones
>>> print_lol(movies,True,1)
    The Holy Grail
    1975
    Terry Jones & Terry Gilliam
    91
        Graham Chapman
            Michael Palin
            John Cleese
            Terry Gilliam
            Eric Idle
            Terry Jones

模块

模块的重要性

上一篇下一篇

猜你喜欢

热点阅读