【head first python】2.共享你的代码 函数模块

#coding:utf-8
#注释代码!
#添加两个注释,一个描述模块,一个描述函数

'''这是nester.py模块,提供了一个名为print_lol()的函数,
这个函数的作用是打印列表,其中可能包含
(也可能不包含)嵌套列表。'''
def print_lol(the_list):
    '''这个函数取一个位置参数,名为the_list,这可以是任何python列表
    (也可以是包含嵌套列表的列表),所指定列表的每个数据项
    回(递归地)输出到屏幕上,每个数据项各占一行。'''
    for item in the_list:
        if isinstance(item,list):
            print_lol(item)
        else:
            print item
print_lol(movies)

模块就是一个包含python代码的文本文件,以.py结尾。

#试着使用
movies = movies = ['The Holy Grail', 1975, 'The Life of Brain', 1979,
          ["Graham Chapman",["Michael Palin","John Cleese","Terry Gilliam","Eric Idle"]]]
print_lol(movies)

【准备发布】

1.为模块创建一个文件夹nester

2.在文件夹中创造一个setup.py文件

#coding:utf-8
from distutils.core import setup
#从python发布工具中导入setup函数

#这些是setup函数的参数
setup(
    name                    ='nester',
    version                    ='1.0.0',
    py_moudles                =['nester'],
    author                    ='HETAO',
    author_email            ='13111300003@163.com',
    url                        ='https://home.cnblogs.com/u/Archimedes/',
    description                ='A simple printer of nested lists',
    )

构建发布

1.构建一个发布文件

2.将发布安装到python本地副本中

 这时nester文件夹中会出现两个新的文件夹,他们是由发布工具创建的

【导入模块并使用】

Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import nester
>>>

 可以看到导入成功了,接下来试着使用它

Python 2.7 (r27:82525, Jul  4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import nester
>>> movies = movies = ['The Holy Grail', 1975, 'The Life of Brain', 1979,
          ["Graham Chapman",["Michael Palin","John Cleese","Terry Gilliam","Eric Idle"]]]

>>> print_lol(movies)

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    print_lol(movies)
NameError: name 'print_lol' is not defined  #python没有找到你的函数!!!
>>> 

这是我们就要认识到一个东西叫做【模块的命名空间】

命名空间i就像是姓氏,正确的使用方式是nester.print_lo(movies)

>>> nester.print_lol(movies)
The Holy Grail
1975
The Life of Brain
1979
Graham Chapman
Michael Palin
John Cleese
Terry Gilliam
Eric Idle
>>> 

 这样就好了

注:如果使用from nester import print_lol 就可以把指定函数增加到当前命名空间,也就是说不用使用nester这个命名空间限定了。

但这种做法并不被提倡,因为在这时候要注意如果当前命名空间中已经定义了一个同名的函数print_lol,那么之前这个函数就会被引入的函数所覆盖而带来麻烦。

【注册PYPI网站】

要在PYPI上发布,就要先注册一个账号(https://pypi.python.org)

截止 【【P49】】

原文地址:https://www.cnblogs.com/Archimedes/p/7141093.html