语法:Python中的修饰器@

在阅读源码时纠结于python中修饰器的原理,在推酷上发现一篇文章感觉讲的不错:python修饰器。还有一篇博客讲的挺好:Decorator深入详解,如果需要更为全面的了解,只能祭出我看到的这篇了,特别的靠谱。decorator全面讲解


个人感觉使用修饰器由两种情况:

  • 一种是功能代码完成后需要添加辅助性功能(例如性能测试、日志记录、调试信息)时用到修饰器;
  • 一种是在软件设计阶段根据实际功能需求添加修饰器。

在Mark Lutz的《Python学习手册》中做出的解释,函数修饰器(function decorator)提供了一种方式,替函数明确了特定的运算方式,也就是将函数报过了另一层,在另一函数的逻辑内实现。
函数修饰器紧挨着函数定义的上一行,有@和后面的元函数(metafunction)即管理另一函数的函数组成
类似于

@decorator_name
def function():
    ......

上面的效果等同于

funtion = decorator_name(function)

修饰器的实例:

import time
def run_time(func):
    def wrapper():
        start = time.clock()
        func()
        end = time.clock()
        print('used time:{}'.format(end-start))
    return wrapper

@run_time
def say_hello():
    print('hello')
print('say_hello.__name__:({})'.format(say_hello.__name__))

运行结果:
fig.1

从运行结果发现,函数say_hello的内置name属性不再是 “say_hello”,变成了“wrapper”。因为修饰器返回的是内部函数的引用。这对我们的程序结构调用带来了不便,好在python中的functool包提供的wraps修饰器可以解决这个问题。

import time
from functools import wraps

def run_time(func):
    @wraps(func)
    def wrapper():
        start = time.clock()
        func()
        end = time.clock()
        print('used time:{}'.format(end-start))
    return wrapper

@run_time
def say_hello():
    print('hello')
print('say_hello.__name__:({})'.format(say_hello.__name__))

运行结果:
这里写图片描述

个人感觉修饰器的作用就是在函数原有功能之外对函数进行扩展,丰富函数的功能。另外,修饰器既可以用于函数,也可以用于类。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值