前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python基础(12)——装饰器

Python基础(12)——装饰器

作者头像
羊羽shine
发布2019-05-28 13:29:03
3430
发布2019-05-28 13:29:03
举报
文章被收录于专栏:Golang开发

python装饰器就是用于拓展原来函数功能的一种函数,这个函数的特殊之处在于它的返回值也是一个函数(函数的指针),使用python装饰器的好处就是在不用更改原函数的代码前提下给函数增加新的功能 给当前代码增加代码执行时间

代码语言:javascript
复制
import time

def func():
    beginTime = time.time()
    print("hello world")
    time.sleep(2)
    print("hello python")
    endTime = time.time()
    print(endTime-beginTime)

func()

如果需要在其他函数也增加代码执行时间,工作存在很大的重复性

代码语言:javascript
复制
import time

def foo():
    print("hello world")
    time.sleep(2)
    print("hello python")


def decorator(func):
    beginTime = time.time()
    func()
    endTime = time.time()
    print(endTime - beginTime)


if __name__=='__main__':
    f = foo
    decorator(f)  # 只有把func()或者f()作为参数执行,新加入功能才会生效
    print("

装饰器表示

代码语言:javascript
复制
import time

def deco(func):
    def wrapper():
        beginTime = time.time()
        func()
        endTime = time.time()
        print(endTime - beginTime)
    return wrapper

@deco
def foo():
    print("hello world")
    time.sleep(2)
    print("hello python")


if __name__=='__main__':
    foo()

带有参数的装饰器

代码语言:javascript
复制
import time


def addDeco(func):
    def wrapper(a,b):
        beginTime = time.time()
        func(a,b)
        endTime = time.time()
        print(endTime - beginTime)

    return wrapper


@addDeco
def bar(a,b):
    print("bar func")
    time.sleep(1)
    print("add result:",a+b)



if __name__=='__main__':
    bar(4,6)
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018.07.16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档