Python装饰器简单用法实例小结

yipeiwu_com6年前Python基础

本文总结分析了Python装饰器简单用法。分享给大家供大家参考,具体如下:

装饰器在python中扮演着很重要的作用,例如插入日志等,装饰器可以为添加额外的功能同时又不影响业务函数的功能。

比如,运行业务函数fun()同时打印运行花费的时间

1. 运行业务函数fun()同时打印运行花费的时间

import time
def dec(fun):
  start = time.time()
  fun()
  end = time.time()
  a = end - start
  print a
def myfun():
  print 'run myfunction'
dec(myfun)

运行结果

(virt2) root@ubuntu:/home/z# python z.py
run myfunction
0.00108599662781

但是每次运行myfun都要调用dec,下面作下变动解决这个问题

2.

import time
def dec(fun):
  def wrap():
    start = time.time()
    fun()
    end = time.time()
    a = end - start
    print a
  return wrap
def myfun():
  print 'run myfunction'
myfun=dec(myfun)
myfun()

运行结果:

(virt2) root@ubuntu:/home/z# python z.py
run myfunction
0.00122618675232

这个装饰器dec就实现了,并且不影响函数myfun功能

3. 装饰器@符

import time
def dec(fun):
  def wrap():
    start = time.time()
    fun()
    end = time.time()
    a = end - start
    print a
  return wrap
@dec
def myfun():
  print 'run myfunction'
myfun()

结果

(virt2) root@ubuntu:/home/z# python z.py
run myfunction
0.000470876693726

使用了@后,就不用给myfun重新赋值了

@dec就相当于myfun=dec(myfun)

例子:

def level(leveel):
  def debug(func):
    def wrapper(*args, **kwargs):
      print("[DEBUG]: enter {}()".format(func.__name__),leveel)
      return func(*args, **kwargs)
    return wrapper
  return debug
@level(leveel='debuging')
def say(something):
  print ("hello {}!".format(something))
say(123)

输出:

('[DEBUG]: enter say()', 'debuging')
hello 123!

'''
class logging(object):
  def __init__(self, func):
    self.func = func
  def __call__(self, *args, **kwargs):
    print ("[DEBUG]: enter function {func}()".format(
      func=self.func.__name__))
    return self.func(*args, **kwargs)
@logging
def say(something):
  print ("say {}!".format(something))
'''
class logging(object):
  def __init__(self, level='INFO'):
    self.level = level
  def __call__(self, func): # 接受函数
    def wrapper(*args, **kwargs):
      print ("[{level}]: enter function {func}()".format(
        level=self.level,
        func=func.__name__))
      func(*args, **kwargs)
    return wrapper #返回函数
@logging(level='INFO')
def say(something):
  print ("say {}!".format(something))
say(123)

输出:

[INFO]: enter function say()
say 123!

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

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

相关文章

python开发之thread实现布朗运动的方法

python开发之thread实现布朗运动的方法

本文实例讲述了python开发之thread实现布朗运动的方法。分享给大家供大家参考,具体如下: 这里我将给大家介绍有关python中thread来实现布朗运动的一个例子 下面是运行效果...

Windows安装Python、pip、easy_install的方法

Windows安装Python、pip、easy_install的方法

安装Python 下载Python安装包 https://www.python.org/downloads/ 图形化安装 选择安装位置 这里安装至D:\Program Files (x8...

python用reduce和map把字符串转为数字的方法

python中reduce和map简介 map(func,seq1[,seq2...]) :将函数func作用于给定序列的每个元素,并用一个列表来提供返回值;如果func为None,fu...

python使用matplotlib库生成随机漫步图

python使用matplotlib库生成随机漫步图

本教程使用python来生成随机漫步数据,再使用matplotlib将数据呈现出来 开发环境 操作系统: Windows10 IDE: Pycharm 2017.1.3 Python...

对Python3 goto 语句的使用方法详解

对Python3 goto 语句的使用方法详解

熟悉 C 语言的小伙伴一定对 goto 语句不陌生,它可以在代码之间随意的跳来跳去,但是好多老鸟都告诫大家,不要使用 goto,因为 goto 会使你的代码逻辑变的极其混乱。 但是有时候...