[Head First Python]2.共享你的代码-函数模块

将模块转换为一个python发布

nester.py 

1- 如果为函数提供一个缺省值,这个函数就是可选的,如参数level = 0

2- end = "" 作为print()BIF的一个参数,会关闭其默认行为(即在输入中自动包含换行)

1 def print_lol(the_list, indent = False, level = 0):
2     for each_item in the_list:
3         if isinstance(each_item,list):
4             print_lol(each_item, indent, level + 1);
5         else:
6             if indent:
7                 for tab_stop in range(level):
8                     print("\t",end='')
9             print(each_item)

创建一个文件夹nester,在此文件夹下,创建setup.py文件

setup.py

from distutils.core import setup

setup(
    name        ='nester',
    version     ='0.1.0',
    py_modules  =['nester'],
    author      ='shelley',
    author_email='shelley@gmail.com',
    url         ='',
    description =' a simple printer of nested lists',
    )

 

文件夹包含2个文件,模块代码放在nester.py中,模块的有关元数据放在setup.py中,现在来构建发布

/nester>python setup.py sdist

 

将发布安装到你的python本地副本中

sudo python setup.py install

 

发布已经准备就绪.

现在已经构建了模块,要使用一个模块,只需要把它导入到你的程序中,或者导入到IDLE shell:

import nester

 

python的所有代码都与一个命名空间关联.主python程序的代码与一个名为__mian__的命名空间关联,将代码放在其单独的模块中时,python会自动创建一个与模块同名的命名空间.所以你的模块中的代码会与一个nester的命名空间关联.

模块名.函数名(参数1,参数2)

nester.print_lol(cast, True)

 

cast.py 

1 #_*_ coding:utf-8 _*_
2 import nester
3 cast = ["hello","kitty",["world",["Jerry"]],"program",["Java","C"],"test"]
4 nester.print_lol(cast, True) #列表cast, 需要缩进True,默认参数缩进数0个tab
5 print("\n")
6 nester.print_lol(cast) #列表cast, 默认参数需要缩进False,默认参数缩进数0个tab
7 print("\n")
8 nester.print_lol(cast, True, 2) #列表cast, 需要缩进True,缩进数2个tab

 

中文注释,需要添加  #_*_ coding:utf-8 _*_

 

 运行

$ python cast.py

 

 

 

posted @ 2013-11-09 15:01  galoishelley  阅读(215)  评论(0编辑  收藏  举报