流畅的Python(五)- 一等函数

2024-01-22 22:52
文章标签 python 函数 流畅 一等

本文主要是介绍流畅的Python(五)- 一等函数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、一等对象

Python函数是一等对象,其满足以下4个条件:

1. 在运行时创建

2.能赋值给变量或数据结构中的元素

3.能作为参数传递给函数

4.能作为函数的返回结果

二、代码示例

1、函数视为对象

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/1/21 15:19
# @Author  : Maple
# @File    : 01-函数视为对象.py
# @Software: PyCharmdef fun(a):"""return一个整数"""return aif __name__ == '__main__':print(fun.__doc__) # return一个整数# 函数fun的类型是function类的一个实例对象print(type(fun)) # <class 'function'>

2、高阶函数

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/1/21 15:22
# @Author  : Maple
# @File    : 02-高阶函数.py
# @Software: PyCharm"""高阶函数是指 接受函数作为参数 或者把函数作为结果返回的函数1.高阶函数是函数2.高阶函数接受函数作为参数或者函数作为返回结果
"""def f1(a):return a * 2if __name__ == '__main__':#1. sorted就是一个高阶函数,参数key接受一个函数作为参数,然后对`可迭代对象`按照指定的规则进行排序fruits = ['bigpear','apple','banana','cherry']sorted_fruite = sorted(fruits,key=len)print(sorted_fruite) # ['apple', 'banana', 'cherry', 'bigpear']#2.高阶函数map示例# 对[0-4]之间的每个数应用f1函数,并返回结果print(list(map(f1,range(5)))) # [0, 2, 4, 6, 8]# 列表推导式的替代方案r1 = [f1(i) for i in range(5)]print(r1) # [0, 2, 4, 6, 8]#3.高阶函数filter示例print(list(map(f1,filter(lambda x: x%2,range(6))))) # [2, 6, 10]# 列表推导式的替代方案r2 = [f1(i) for i in range(6) if i % 2]print(r2) #[2, 6, 10]

3、可调用对象

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/1/21 15:34
# @Author  : Maple
# @File    : 03-可调用对象.py
# @Software: PyCharm"""Python数据模型中的7种可调用对象
1.用户定义的函数:使用def语句或者lambda表达式创建
2.内置函数,如len
3.内置方法,如dict.get
4.方法:在类中定义的函数
5.类
6.类的实例
7.生成器函数
"""
import randomclass BingoCage:def __init__(self,items):self._items = list(items)random.shuffle(self._items)def pick(self):try:return self._items.pop()except IndexError:raise LookupError('pick from empty BingoCage')# 内置call方法,实现BingoCage类的实例是可调用的def __call__(self):return self.pick()if __name__ == '__main__':# 1.使用callable判断对象 是否可调用r1 = [callable(obj) for obj in (abs,str,12)]print(r1) # [True, True, False]# 2. 判断自定义类的实例是否可调用bingo = BingoCage(range(3))# 实例对象是可调用对象print(callable(bingo)) # True# 实例对象是可调用的r= bingo()print(r) # 0

4、仅限关键字参数

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/1/21 14:56
# @Author  : Maple
# @File    : 04-仅限关键字参数.py
# @Software: PyCharmdef tag(name,*content,cls=None,**attrs):"""生成一个或多个html标签"""if cls is not None:attrs['class'] = clsif attrs:attrs_str = ''.join(' %s="%s"' %(attr,value)for attr,value in sorted(attrs.items()))else:attrs_str = ''if content:return '\n'.join('<%s%s>%s</%s>' %(name,attrs_str,c,name)for c in content)else:return '<%s%s />' %(name,attrs_str)def f(a,*,b):"""函数参数中间放了一个*,调用函数时必须以关键字参数的形式传入b的值"""return a,bif __name__ == '__main__':#1.tag标签测试## 1-1 案例1html1 = tag('br')print(html1) # <p>hello</p>## 1-2 案例2html2 = tag('p','hello')print(html2) # <p>hello</p>## 1-3 案例3html3 = tag('p','Java','world')"""<p>Java</p><p>world</p>"""print(html3)## 1-4 案例4html4 = tag('p','hello','world',cls='size')"""<p class="size">hello</p><p class="size">world</p>"""print(html4)## 1-5 案例5my_tag = {'name':'img', 'title':'Sunset','src': 'sunset.jpg', 'cls': 'framed'}html5 = tag(**my_tag)print(html5) # <img class="framed" src="sunset.jpg" title="Sunset" />#2.函数f测试#  TypeError: f()takes 1 positional argument but 2 were given# f(1,3)a, b = f(1,b= 1)print(a,b) # 1 1

5、函数参数信息获取

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/1/21 16:02
# @Author  : Maple
# @File    : 05-函数参数信息获取.py
# @Software: PyCharmdef tag(name,*content,cls=None,**attrs):"""生成一个或多个html标签"""if cls is not None:attrs['class'] = clsif attrs:attrs_str = ''.join(' %s="%s"' %(attr,value)for attr,value in sorted(attrs.items()))else:attrs_str = ''if content:return '\n'.join('<%s%s>%s</%s>' %(name,attrs_str,c,name)for c in content)else:return '<%s%s />' %(name,attrs_str)if __name__ == '__main__':from inspect import signature# 1. 获取函数参数信息sig = signature(tag)print(type(sig)) # 返回一个inspect.Signature类的实例对象print(str(sig)) # (name, *content, cls=None, **attrs)# inspect.Signature对象有一个parameters属性,将参数名与inspect.Parameter对象对应起来,同时各个Parameter对象也有自己的属性,包括name,default,kind# 如下示例:name是参数名,param是Parameter对象,该对象封装了参数的name(参数名),default(参数默认值)和kind(参数类型)属性for name,param in sig.parameters.items():"""打印结果POSITIONAL_OR_KEYWORD : name = <class 'inspect._empty'>VAR_POSITIONAL : content = <class 'inspect._empty'>KEYWORD_ONLY : cls = NoneVAR_KEYWORD : attrs = <class 'inspect._empty'>""""""补充说明POSITIONAL_OR_KEYWORD代表`定位参数和关键字参数`VAR_POSITIONAL代表`定位参数元组`KEYWORD_ONLY代表`仅限关键字参数`inspect._empty表示没有默认值"""print(param.kind,':',name,'=',param.default)# 2.给函数形参 绑定实参my_tag = {'name': 'img', 'title': 'Sunset','src': 'sunset.jpg', 'cls': 'framed'}bound_args = sig.bind(**my_tag)for name,value in bound_args.arguments.items():"""打印结果name = imgcls = framedattrs = {'title': 'Sunset', 'src': 'sunset.jpg'}"""print(name,'=',value)del my_tag['name']# TypeError: missing a required argument: 'name'# 因为name是必须传递的参数,却没有传入# bound_args = sig.bind(**my_tag)

6、函数注解

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/1/21 21:48
# @Author  : Maple
# @File    : 06-函数注解.py
# @Software: PyCharm"""
1. 函数声明的各个参数可以在:之后增加注解表达式
2. 如果参数有默认值,注解放在参数和'='之间,如本例中的'int>0'
3. 如果想注解返回值,可以在)和':' 之间田间->和一个表达式,如本例的 ->str
"""
def clip(text:str,max_len:'int>0'=80) ->str:"""在max_len前面或后面的第一个空格处截断文本"""end = Noneif len(text) > max_len:space_before = text.rfind(' ',0, max_len)# 如果能够找到spaceif space_before >=0:end = space_beforeelse:space_after = text.rfind('' ,max_len)if space_after >= 0:end = space_afterif end is None: # 没找到空格end = len(text)return text[:end].rstrip()if __name__ == '__main__':# 获取函数注解信息print(clip.__annotations__) # {'text': <class 'str'>, 'max_len': 'int>0', 'return': <class 'str'>}# 从函数签名中获取注解信息from inspect import signaturesig = signature(clip)# 打印注解返回值print(sig.return_annotation) #<class 'str'># 打印参数注解for param in sig.parameters.values():# sig.parameters有一个属性annotation,里面封装了参数注解值note = repr(param.annotation).ljust(13)"""打印结果<class 'str'> : text = <class 'inspect._empty'>'int>0'       : max_len = 80"""print(note,':', param.name,'=', param.default)

7、函数式编程包

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/1/21 22:03
# @Author  : Maple
# @File    : 07-函数式编程包.py
# @Software: PyCharmfrom functools import reduce
from operator import mul# operator模块
def fact(n):# 计算n!return reduce(mul,range(1,n+1))if __name__ == '__main__':# 1. operator模块中的mul应用r1= fact(5)print(r1) # 120# 2. operator模块中的itemgetter应用metro_data = [('Tokyo','JP',36.933,(35.689722,139.691667)),('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889)),('Mexico City', 'MX', 20.142, (19.433333, -99.133333)),]from operator import itemgetter"""itemgetter(1)等价于:lambda x: x[1]"""for city in sorted(metro_data,key=itemgetter(1)):print(city)print('------------------------')# cc_name是一个函数,等价于lambda x: (x[1],x[0])cc_name = itemgetter(1,0)for city in metro_data:"""打印结果:       ('JP', 'Tokyo')('IN', 'Delhi NCR')('MX', 'Mexico City')"""# 调用cc_nameprint(cc_name(city))print('------------------------')# 3. operator模块中的attrgetter应用# 相比itemgetter,attrgetter能够获取嵌套属性的值from collections import namedtupleLatLong = namedtuple('LatLong','lat long')city_info = [('Tokyo', 'JP', (35.689722, 139.691667)),('Delhi NCR', 'IN',  (28.613889, 77.208889)),('Mexico City', 'MX', (19.433333, -99.133333)),]City = namedtuple('Citys','name country coord')citys = [City(name,country, LatLong(coord[0],coord[1])) for name,country,coord in city_info]# 提取第一座城市的维度print(citys[0].coord.lat) # 35.689722from operator import attrgetter# 自定义attrgetter:name_lat,其等价于lambda x: (x.name,x.coord.lat)name_lat = attrgetter('name','coord.lat')for city in citys:"""打印结果('Tokyo', 35.689722)('Delhi NCR', 28.613889)('Mexico City', 19.433333)"""# 调用name_latprint(name_lat(city))# 4. operator模块中的methodcaller应用(类似于Java中的反射)from operator import methodcaller# f具备的功能是:替换空格为'-'f = methodcaller('replace',' ','-')s = 'Hello world'print(f(s)) # Hello-world

8、高阶函数partial

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/1/22 19:42
# @Author  : Maple
# @File    : 08-高阶函数partial.py
# @Software: PyCharm"""
接受一个函数作为参数,然后创建一个新的可调用对象,把原函数的某些参数固定
"""from functools import partial
from operator import mul# mul函数的功能是计算两个数的乘积
# 以下方式将mul的第一个参数固定为3
triple = partial(mul,3)if __name__ == '__main__':# 1. triple调用:3 * 4print(triple(4)) # 12# 2.map只能接受 单一参数的函数,所以并不能传递mul作为参数.这里也演示了partial的一个应用场景print(list(map(triple,range(1,10)))) # [3, 6, 9, 12, 15, 18, 21, 24, 27]# 字符规范化(可参考第4章字符串规范化部分)的应用场景举例import unicodedata# 定义一个nfc函数,默认参数是'NFC'nfc = partial(unicodedata.normalize,'NFC')s1 = 'café's2 =  'cafe\u0301'print(nfc(s1) == nfc(s2)) # True## 补充: 原生的写法unicodedata.normalize('NFC',s1) == unicodedata.normalize('NFC',s2)

这篇关于流畅的Python(五)- 一等函数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/634502

相关文章

Python的Darts库实现时间序列预测

《Python的Darts库实现时间序列预测》Darts一个集统计、机器学习与深度学习模型于一体的Python时间序列预测库,本文主要介绍了Python的Darts库实现时间序列预测,感兴趣的可以了解... 目录目录一、什么是 Darts?二、安装与基本配置安装 Darts导入基础模块三、时间序列数据结构与

Python正则表达式匹配和替换的操作指南

《Python正则表达式匹配和替换的操作指南》正则表达式是处理文本的强大工具,Python通过re模块提供了完整的正则表达式功能,本文将通过代码示例详细介绍Python中的正则匹配和替换操作,需要的朋... 目录基础语法导入re模块基本元字符常用匹配方法1. re.match() - 从字符串开头匹配2.

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

通过Docker容器部署Python环境的全流程

《通过Docker容器部署Python环境的全流程》在现代化开发流程中,Docker因其轻量化、环境隔离和跨平台一致性的特性,已成为部署Python应用的标准工具,本文将详细演示如何通过Docker容... 目录引言一、docker与python的协同优势二、核心步骤详解三、进阶配置技巧四、生产环境最佳实践

Python一次性将指定版本所有包上传PyPI镜像解决方案

《Python一次性将指定版本所有包上传PyPI镜像解决方案》本文主要介绍了一个安全、完整、可离线部署的解决方案,用于一次性准备指定Python版本的所有包,然后导出到内网环境,感兴趣的小伙伴可以跟随... 目录为什么需要这个方案完整解决方案1. 项目目录结构2. 创建智能下载脚本3. 创建包清单生成脚本4

Python实现Excel批量样式修改器(附完整代码)

《Python实现Excel批量样式修改器(附完整代码)》这篇文章主要为大家详细介绍了如何使用Python实现一个Excel批量样式修改器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录前言功能特性核心功能界面特性系统要求安装说明使用指南基本操作流程高级功能技术实现核心技术栈关键函

python获取指定名字的程序的文件路径的两种方法

《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下

使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解

《使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解》本文详细介绍了如何使用Python通过ncmdump工具批量将.ncm音频转换为.mp3的步骤,包括安装、配置ffmpeg环... 目录1. 前言2. 安装 ncmdump3. 实现 .ncm 转 .mp34. 执行过程5. 执行结

Python实现批量CSV转Excel的高性能处理方案

《Python实现批量CSV转Excel的高性能处理方案》在日常办公中,我们经常需要将CSV格式的数据转换为Excel文件,本文将介绍一个基于Python的高性能解决方案,感兴趣的小伙伴可以跟随小编一... 目录一、场景需求二、技术方案三、核心代码四、批量处理方案五、性能优化六、使用示例完整代码七、小结一、

Python中 try / except / else / finally 异常处理方法详解

《Python中try/except/else/finally异常处理方法详解》:本文主要介绍Python中try/except/else/finally异常处理方法的相关资料,涵... 目录1. 基本结构2. 各部分的作用tryexceptelsefinally3. 执行流程总结4. 常见用法(1)多个e