https://www.cnblogs.com/sweet-i/p/11177063.html #1.函数变量 def fun(): print('hello') #函数调用 fun() #hello #打印函数变量 print(fun)#<function fun at 0x000001F09EB35160> #2.嵌套函数--一个函数里面包含另一函数的定义 def func1(): def func2(): print('hello') func1()#func2没有执行 #想要func2执行,两种方法 #2.1调用func2 def func1(): def func2(): print('hello') func2()#调用func2 func1() #2.2返回func2的函数变量 def func1(): def func2(): print('hello') return func2 #返回函数变量 返回到func1处 注意不要加括号 res=func1() print(res)#<function func1.<locals>.func2 at 0x000001E321E5EEE0>返回的是func2的函数地址 res()#res()==func2() 运行结果是hello #3.返回函数 2.2就是返回函数 # import time def func1(): time.sleep(3) print('in func1') def func2(): time.sleep(5) print('in func2') def timer0(func): start=time.time() func() print(time.time()-start) timer0(func1) #这种方式改变了func1的调用方式 #func1()-->func1 #in func1 #3.006218910217285 # 装饰器 #装饰器的功能 #在不改变原函数以及调用方式的情况下对原函数功能的拓展 #计时器 def timer(func): def inner(): #闭包函数 start=time.time() func() print(time.time()-start) return inner func1=timer(func1)#==innner func1()#这种调用方式没有变 #in func1 #3.006218910217285 #装饰器升级 #为了简化装饰器的调用,用语法糖@装饰器名称调用 @timer #语法糖==func2=timer(func2) def func2(): time.sleep(5) print('in func2') func2() #还是原来的调用方式 我们直接得到 #in func2 #5.003789186477661 #带参数的装饰器
python装饰器和语法糖
最新推荐文章于 2024-06-13 16:50:37 发布
本文介绍了Python中的函数基础知识,包括函数定义、调用及变量打印。深入探讨了嵌套函数的两种执行方式,并展示了如何返回函数。接着讲解了装饰器的概念,用于在不改变原函数的情况下拓展其功能,如实现计时器。最后提到了装饰器的使用语法糖@,并展示了带参数的装饰器应用。
摘要由CSDN通过智能技术生成