Head First Python 读书笔记(二)

第四章 :函数与模块

  • 定义函数:def
  • 函数注释文档
def icessun():
    # 这也是注释,下面是函数文档注释,描述函数的用途
    """this is function document as docstring"""
    vowels=set('aeiou')
    word = input("provide a word to search for vowels:")
    found=vowels.intersection(set(word))
    for vowel in found:
        print(vowel)
  • 上面这种函数注释可以,下面这种函数注解是针对python3的也行
def search4letters(phrase:str,letter:str)->set:
    """return a set of the letter found in phrase."""
    return set(letter).intersection(set(phrase))

参数旁边的表示:希望传入的参数类型;参数列表后面的箭头表示:返回值是一个集合;这样做只是为了方便程序员阅读,程序不会去强制校验。
- 如何看注释,而不用读代码:在IDLE的编辑器中按F5运行代码,在python shell中输入help(函数名字)
函数文档

  • 允许将任何对象作为参数传递给函数,而且允许将任何对象作为返回值返回
  • 函数参数默认值,调用时没有提供参数值,就是要函数中的默认值。
def search4letters(phrase:str,letter:str='aeiou')->set:
    """return a set of the letter found in phrase."""
    return set(letter).intersection(set(phrase))
  • 关键字参数赋值,调用函数时,直接使用函数中的形参去赋值(一般是按照形参的位置赋值)
def search4letters(phrase:str,letter:str='aeiou')->set:

search4letters(letter='xyz',phrase='galaxy')

函数共享

  • 模块就是包含函数的文件,把需要共享的函数单调放在一个文件里面,作为模块共享,使用时:import 模块名字即可
  • 模块存放的位置:

    • 当前工作目录
    • 你的解释器的site-packages位置:使用setuptools安装
    • 标准库位置

模块本地导入

在桌面创建一个文件夹,把要共享的模块放入其中;运行cmd,切换到新建的文件夹下,调用python解释器:py -3(windows下的命令),使用import 模块名字导入模块,使用模块中的函数。这个新建的文件夹就会被解释器当做我们的当前工作目录。

  • 模块安装到site-packages,使用的setuptools工具

    • 创建一个发布描述
    • 生成一个发布文件
    • 安装发布文件

两个必要的发布描述文件:setup.py and README.txt

#  setup.py 文件 描述我们的模块  README.txt  文件要有,但是内容可选
from setuptools import setup
setup(name='functionTest',
          version='1.0',
          description='the first modules by icessun',
          author='icessun',
          author_email='[email protected]',
          url='headfirstlabs.com',
          py_modules=['functionTest'],
          )

创建发布描述

创建发布消息 ,执行的命令

创建发布消息 ,成功返回的消息

模块中文件的变化

可以安装的文件(包)在dist文件夹(由setuptools创建)里面,里面包含模块的源代码

产生的包,发布文件

  • 使用pip安装上面生成的包

安装发布文件

到此,已经成功的创建了一个发布文件,可以直接把这个发布文件拷给对方,使用pip安装。或者是直接把这个发布文件上传到PyPI,让所有的程序员都可以使用。

猜你喜欢

转载自blog.csdn.net/icessunt/article/details/80907121