Python中的装饰器

装饰器,是Python中较为独特的语法糖之一。以下是官方文档定义:

A function returning another function, usually applied as a function transformation using the @wrapper syntax. Common examples for decorators are classmethod() and staticmethod().

The decorator syntax is merely syntactic sugar, the following two function definitions are semantically equivalent:

def f(...):
    ...
f = staticmethod(f)

@staticmethod
def f(...):
    ...

The same concept exists for classes, but is less commonly used there. See the documentation for function definitions and class definitions for more about decorators.

英语渣渣尬翻:

大意:一个函数返回在另一个函数中,通常使用 @wrapper 来实现函数的转换。
装饰器语法仅仅是语法糖,例子中的两个函数在语义上是等价的。

之前见到一个例子很贴切足以解释装饰器:计算一个函数的运行时间

不用装饰器的人会这样写

import time

def func1(func):
    startTime = time.time()
    func()
    endTime = time.time()
    secr = (endTime - startTime) * 1000
    print('spend %f' %(secr))

def func():
    print("hello")

if __name__ == '__main__':
   func1(func)

每次监测时间的时候就会将被检测的函数作为检测函数的参数

用装饰器的人会这么写

import time

def deco(func):
    def wrapper():
        startTime = time.time()
        func()
        endTime = time.time()
        secr = (endTime - startTime) * 1000
        print('spend %f' %(secr))
    return wrapper

@deco
def func():
    print("hello")

if __name__ == '__main__':
    func()

那么之后定义需要监测时间的函数的时候,只需要在前面加上@deco 即可,简单便捷,不是吗?
最后还需要说明两点:装饰器是可叠加使用的,还有装饰器可以加参数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值