python装饰器和语法糖

本文介绍了Python中的函数基础知识,包括函数定义、调用及变量打印。深入探讨了嵌套函数的两种执行方式,并展示了如何返回函数。接着讲解了装饰器的概念,用于在不改变原函数的情况下拓展其功能,如实现计时器。最后提到了装饰器的使用语法糖@,并展示了带参数的装饰器应用。
摘要由CSDN通过智能技术生成
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

#带参数的装饰器
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值