#1.函数对象
#python的函数也是对象,故而可以传递。
def echo(msg):
print(msg)
def callfunc(f,arg):
f(arg)
foo=echo
callfunc(foo,'hello,world')
#2.除了系统给自定义的属性,还可以给函数对象自定义任意属性。
echo.attr1='user-defined attribute'
echo.count=0
echo.count+=1
#3.函数注释:Annotations
def fun(a:'annoa',b:'annob',c:'annoc'='default value')->int:
print(a,b,c)
#注释可以是任何东西,可选.一般可用于指定参数类型.
#在注释后面也可以为参数指定默认值.
#注释以Dictionary的形式保存在函数对象的__annotations__属性中.
#4. lambda表达式
lambda表达式返回一个函数,即匿名函数.函数体只有一个表达式.
一个简单例子:
f=lambda x,y,z=7:x+y+z
f(3,4,5)
此处为z指定了默认值.此外,lambda表达式还可以嵌套.
#5.三个有意思的函数:map,filter,reduce
map,filter,reduce
------------------------
map(func,iterator) ->func[x] for x in iterator
filter(func,iterator) -> x if func(x) for x in iterator
functools.reduce(func,iterator) :将iterator[0]作为初始值x,依次取y=iterator[1:];计算x=func(x,y);返回最终的x.
---------------
扫一扫,获取更多信息