一等对象之函数

本文详细介绍了Python中函数作为一等对象的概念,包括它们如何被赋值、作为参数传递和作为返回值。此外,还探讨了高阶函数,如map、sorted、filter和reduce的使用。另外,提到了匿名函数、函数内省以及函数的一些属性,如docstring、user-defined attributes、annotations等。
摘要由CSDN通过智能技术生成

Python 函数

  • 什么是一等对象
  • 高阶函数
  • 匿名函数
  • 函数内省

1 一等对象

在Python中,函数是一等对象。一等对象定义如下:

  • 运行时创建
  • 能赋值给变量或数据结构中的元素
  • 能作为参数传递给函数
  • 能作为函数返回值

即,函数和变量没什么“不同”,都是一等对象。

2 函数即对象

def factorial(n):
    """return n!"""
    return 1 if n<2 else n*factorial(n-1)
>>> fact = factorial#把函数赋值给变量
>>> fact(5)
120
>>> list(map(factorial,range(7)))#将函数作为参数传递
[1, 1, 2, 6, 24, 120, 720]

3 高阶函数

接受函数为参数,或者把函数作为结果返回的函数是高阶函数。Python常见的高阶函数有:

  • map
  • sorted
  • filter
  • reduce

3.1 map函数

map(func, *iterables),第一个参数func为函数,第二个参数iterables为一个或多个序列。

map函数作用为对指定序列做映射:把序列中的每个元素传入func,并返回映射后的序列。

>>> map(factorial,range(7))#返回一个迭代器
<map object at 0x...>
>>> list(map(factorial,range(7)))#list获取迭代器内容
[1, 1, 2, 6, 24, 120, 720]#序列为0-6传入factorial函数的返回值:0!-6!

3.2 sorted函数

sorted(iterable, / , *, key=None, reverse=False)

sorted函数作用为对指定序列排序,参数key可传入“单参数函数”作为排序依据,reverse=False表示顺序排序(从小到大)。

>>> words = ['world','apple','hello','banana','fig']
>>> sorted(words)	#默认从小到大排序
['apple', 'banana', 'fig', 'hello', 'world']
>>> sorted(words, key=len)	#按单词长度排序
['fig', 'world', 'apple', 'hello', 'banana']
>>> sorted(words, key=len, reverse=True)	#按单词长度逆序排序
['banana', 'world', 'apple', 'hello', 'fig']
>>> 
>>> d = dict(one=1,two=2,three=3,four=4,fife=5,six=6)
>>> d
{
   'fife': 5, 'two': 2, 'four': 4, 'six': 6, 'one': 1, 'three': 3}
>>> sorted(d.items(
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值