流畅的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中的魔术方法__new__详解

《Python中的魔术方法__new__详解》:本文主要介绍Python中的魔术方法__new__的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、核心意义与机制1.1 构造过程原理1.2 与 __init__ 对比二、核心功能解析2.1 核心能力2.2

Python虚拟环境终极(含PyCharm的使用教程)

《Python虚拟环境终极(含PyCharm的使用教程)》:本文主要介绍Python虚拟环境终极(含PyCharm的使用教程),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录一、为什么需要虚拟环境?二、虚拟环境创建方式对比三、命令行创建虚拟环境(venv)3.1 基础命令3

Python Transformer 库安装配置及使用方法

《PythonTransformer库安装配置及使用方法》HuggingFaceTransformers是自然语言处理(NLP)领域最流行的开源库之一,支持基于Transformer架构的预训练模... 目录python 中的 Transformer 库及使用方法一、库的概述二、安装与配置三、基础使用:Pi

Python 中的 with open文件操作的最佳实践

《Python中的withopen文件操作的最佳实践》在Python中,withopen()提供了一个简洁而安全的方式来处理文件操作,它不仅能确保文件在操作完成后自动关闭,还能处理文件操作中的异... 目录什么是 with open()?为什么使用 with open()?使用 with open() 进行

Python中使用正则表达式精准匹配IP地址的案例

《Python中使用正则表达式精准匹配IP地址的案例》Python的正则表达式(re模块)是完成这个任务的利器,但你知道怎么写才能准确匹配各种合法的IP地址吗,今天我们就来详细探讨这个问题,感兴趣的朋... 目录为什么需要IP正则表达式?IP地址的基本结构基础正则表达式写法精确匹配0-255的数字验证IP地

MySQL高级查询之JOIN、子查询、窗口函数实际案例

《MySQL高级查询之JOIN、子查询、窗口函数实际案例》:本文主要介绍MySQL高级查询之JOIN、子查询、窗口函数实际案例的相关资料,JOIN用于多表关联查询,子查询用于数据筛选和过滤,窗口函... 目录前言1. JOIN(连接查询)1.1 内连接(INNER JOIN)1.2 左连接(LEFT JOI

使用Python实现全能手机虚拟键盘的示例代码

《使用Python实现全能手机虚拟键盘的示例代码》在数字化办公时代,你是否遇到过这样的场景:会议室投影电脑突然键盘失灵、躺在沙发上想远程控制书房电脑、或者需要给长辈远程协助操作?今天我要分享的Pyth... 目录一、项目概述:不止于键盘的远程控制方案1.1 创新价值1.2 技术栈全景二、需求实现步骤一、需求

MySQL中FIND_IN_SET函数与INSTR函数用法解析

《MySQL中FIND_IN_SET函数与INSTR函数用法解析》:本文主要介绍MySQL中FIND_IN_SET函数与INSTR函数用法解析,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一... 目录一、功能定义与语法1、FIND_IN_SET函数2、INSTR函数二、本质区别对比三、实际场景案例分

Python 迭代器和生成器概念及场景分析

《Python迭代器和生成器概念及场景分析》yield是Python中实现惰性计算和协程的核心工具,结合send()、throw()、close()等方法,能够构建高效、灵活的数据流和控制流模型,这... 目录迭代器的介绍自定义迭代器省略的迭代器生产器的介绍yield的普通用法yield的高级用法yidle

使用Python将JSON,XML和YAML数据写入Excel文件

《使用Python将JSON,XML和YAML数据写入Excel文件》JSON、XML和YAML作为主流结构化数据格式,因其层次化表达能力和跨平台兼容性,已成为系统间数据交换的通用载体,本文将介绍如何... 目录如何使用python写入数据到Excel工作表用Python导入jsON数据到Excel工作表用