python语法笔记---返回函数、匿名函数lambda、装饰器decorator

def lazy_sum(*args): #*args:输入参数或参数序列
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
f=lazy_sum(1,2,3) #给lazy_sum赋值,但此时返回数据是sum函数
print(f())
#必须通过f()对f进行调用,f是对lazy_sum赋值后的函数,打印结果为6

函数lazy_sum中又定义了函数sum,并且,内部函数sum可以引用外部函数lazy_sum的参数和局部变量,当lazy_sum返回函数sum时,相关参数和变量都保存在返回的函数中,这种程序结构称作“闭包

匿名函数举例
lambda x: x * x # 左 x是函数参数

装饰器:Decorator
def log(func): #定义log Decorator
def wrapper(*args, **kw):
print(‘call %s():’ % func.name) #调用装饰器参数函数:func
return func(*args, **kw)
return wrapper

@log #调用decorator :log,相当于now = log(now)
def now():
print(‘2015-3-25’)

#调用decorator过程:log(now)–return wrapper,wrapper函数–执行print(‘call %s():’ % func.name),
最终@log执行结果是打印:call func.name()即:call now()

def log(text): #定义带输入参数的decorator-log,三层
def decorator(func):
def wrapper(*args, **kw):
print(’%s %s():’ % (text, func.name)) #打印str-text str-func # #name ()
return func(*args, **kw)
return wrapper
return decorato

@log(‘execute’) # ‘execute’-输入参数,now函数是func,exacute是text
def now():
print(‘2015-3-25’)
print(now()) #打印:exacute now
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值