【head first python】2.共享你的代码 函数模块
2017-08-05 12:24
405 查看
#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】】
相关文章推荐
- 《head first python》— 函数定义、模块与发布、共享代码
- Head First Python---------(一)第一章(初识Python__人人都爱列表)、第二章(共享你的代码__函数模块)、第三章(文件与异常__处理错误)
- Head_first_python 第二章共享你的代码 函数模块
- 笔记:HeadFirstPython(2)共享你的代码
- Python初入门(二) 可共享的函数模板(Head First Python 第二章 共享你的代码)
- Head First Python之2函数模块
- 《Head First Python》学习笔记02 模块和函数参数缺省值
- Head First Python 第二章 函数模块&第三章 文件与异常&第四章 持久存储&第五章 处理数据
- Python初入门(六)(Head First Python 第六章 打包代码与数据 ,字典,类与继承)
- head.First.python:注册pypi、上传代码、更新代码
- HeadFirstPython---------(四)第六章(定制数据对象__打包代码与数据)
- head first python 第二章代码
- Python学习-共享模块代码
- Head First Python(如何向PYPI发布你的代码)学习笔记
- Head First Python代码实践(第六章)有注释
- [Head First Python]6. 定制数据对象:打包代码与数据
- Python3基础 创建一个模块 导入并调用其中的函数 主代码与模块代码在同一文件夹下
- Python 共享和上传函数模块到PyPI
- 共享python代码模块
- Python练习代码 -- 模块和函数