python语法糖@和闭包的理解

python的语法糖@和闭包的简单理解

@:@func1修饰的函数func3会作为func1的参数
闭包:三个条件:

  1. 有内嵌函数
  2. 内嵌函数调用了外部函数的变量
  3. 外部函数返回内部函数地址(函数名不加括号)
    外部函数称为闭包函数。
    在调用闭包函数时func3=func1,这样func3就获得了func2的地址,但是由于不在同一个命名空间,func3修改不了func1中的变量所以有个保护作用。
def func1(func3):#这个叫decorator
	def func2():#里面这个函数其实叫wrapper
		print('before the func,execute sth...')
		#这里就写在执行func3前执行的功能,其实就实现func3功能的扩展
		func3
		print('after the func,execute sth...')
	return func2#返回wrapper的地址
#调用:
@func1
def func3():
    pass
func3()
#用@func1之后就使在调用func3时,
#看wrapper中,func3()执行前后都会再执行一些东西,就实现了对func3的扩展
#另一种情况:
def dec():
    def wrapper(g):
        print('before')
        g()
        print('after')
    return wrapper
@dec()
def test():
    print('Hello!')
#这里的test不能被调用,因为@dec()相当于是#@wrapper,直接把test()给了wrapper。
注意:
@func1
def func3()pass
func3	
相当于
def func3():
    pass
func3=func1(func3)	
func3()
叠层:
@decorator1
@decorator2
def func4():
    pass
func4()	
这里先decorator2,再decorator1

注意如果没有写func4(),即没有调用func4(),则不会执行wrapper()易错
带参数的情况:

def decorator_maker(a,b):
    print('I am the decorator maker!')
    def decorator(func):
        print('I am the decorator!')
        def wrapper():
            print('I am the wrapper !')
            func()
            print('wrapper calling is over!')
        print('decorator calling is over!')
        return wrapper
    print('decrator_maker calling is over !')
    return decorator
@decorator_maker('A',"B")
def func5():
    print('I am the func1')
func5()

函数名和该函数的意义相同。
为了给decorator传递参数,可以向decorator_maker传递,由于命名空间:三个函数都可以使用该参数,此外wrapper还可以使用被修饰的函数func5

  • 注意@decorator_maker()这里是调用函数
  • 可以在decorator_maker()中多定义几个装饰器
  • 注意@在该模块被导入时就被装饰了,和import一样。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值