python装饰器常见使用方法分析

yipeiwu_com6年前Python基础

本文实例讲述了python装饰器常见使用方法。分享给大家供大家参考,具体如下:

python 的装饰器,可以用来实现,类似spring AOP 类似的功能。一样可以用来记录某个方法执行前做什么,执行后做什么,或者用来记录日志,运行的时间等,更有甚者,用这个来做权限拦截,也未尝不可。从两个方面来描述python 的装饰模式:

1. 对普通方法的装饰

2. 对在 class 类中的方法的装饰,不需要给参数的情况

3. 对在 class 类中的方法的装饰,需要给参数的情况

一,对普通方法的装饰。比如,要计算一个一个方法执行的时间.

#coding:utf-8
import time
def timeit(func):
  def wrapper(*args, **kv):
    start = time.clock()
    print '开始执行'
    func(*args, **kv)
    end =time.clock()
    print '花费时间:', end - start
  return wrapper
@timeit
def foo():
  print 'in foo()'
if __name__=='__main__':
  foo()

运行结果:

开始执行
in foo()
花费时间: 6.55415628267e-05

可以看到,计算出了时间差。而不是像普通方法一样,写在一个函数里面实现。

二、对在 class 类中的方法的装饰,不需要给参数的情况

#coding:utf-8
import time
def timeit(func):
  def wrapper(*args, **kv):
    start = time.clock()
    print '开始执行'
    func(*args, **kv)
    end =time.clock()
    print '花费时间:', end - start
  return wrapper
class MySpendTime(object):
  def __init__(self):
    pass
  @timeit
  def foo(self):
    print 'in foo()'
spendtime=MySpendTime()
spendtime.foo()

运行结果:

开始执行
in foo()
花费时间: 4.42208134735e-05

三、对在 class 类中的方法的装饰,需要给参数的情况

#coding:utf-8
'''
Created on 2012-11-1
@author: yihaomen.com
'''
def UpdateUI(msg, step):
  print u"内容:", msg
  print u"步骤:到第%s步了" % step
  def dec(func):
    def wapper(self, *args, **kwargs):
      func(self,*args, **kwargs)
    return wapper
  return dec
class Command(object):
  def Excute(self):
    self.Work1st()
    self.Work2nd()
    self.Work3rd()
  @UpdateUI("开始第一步","1")
  def Work1st(self):
    print "Work1st"
  @UpdateUI("开始第二步", 2)
  def Work2nd(self):
    print "Work2nd"
  @UpdateUI("开始第三步", 3)
  def Work3rd(self):
    print "Work3rd"
if __name__=="__main__":
  command = Command()
  command.Excute()

运行结果:

内容: 开始第一步
步骤:到第1步了
内容: 开始第二步
步骤:到第2步了
内容: 开始第三步
步骤:到第3步了
Work1st
Work2nd
Work3rd

更多关于Python相关内容可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

python基础 range的用法解析

range基本用法: range:顾头不顾尾 range(10)--返回0-9的数字 ey: for i in range(10): print(i) result:0...

小结Python用fork来创建子进程注意事项

自己随手写了Python下 fork 进程的测试代码(来说明这个问题不一定完全合适): def fork(a): def now(): import datetime re...

Python中import导入上一级目录模块及循环import问题的解决

import上一级目录的模块 python中,import module会去sys.path搜索,sys.path是个列表,并且我们可以动态修改。 要import某个目录的module,...

python高级特性和高阶函数及使用详解

python高级特性和高阶函数及使用详解

python高级特性 1、集合的推导式 •列表推导式,使用一句表达式构造一个新列表,可包含过滤、转换等操作。 语法:[exp for item in collection i...

python读写csv文件方法详细总结

python提供了大量的库,可以非常方便的进行各种操作,现在把python中实现读写csv文件的方法使用程序的方式呈现出来。 在编写python程序的时候需要csv模块或者pandas模...