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数据结构之线性表的顺序存储结构

用Python仿照C语言来实现线性表的顺序存储结构,供大家参考,具体内容如下 本文所采用的数据结构模板为 《数据结构教程》C语言版,李春葆、尹为民等著。 该篇所涉及到的是线性表的顺序存...

django连接mysql配置方法总结(推荐)

最近在学习django,学到第五章模型时,需要连接数据库,然后,在这里分享一下方法。 起初是不知道怎样配置mysql数据库,但是还好,django的官网上面有相关的配置方法,下面就直接...

Python中numpy模块常见用法demo实例小结

本文实例总结了Python中numpy模块常见用法。分享给大家供大家参考,具体如下: import numpy as np arr = np.array([[1,2,3],...

python编程实现希尔排序

python编程实现希尔排序

观察一下”插入排序“:其实不难发现她有个缺点:   如果当数据是”5, 4, 3, 2, 1“的时候,此时我们将“无序块”中的记录插入到“有序块”时,估计俺们要崩盘,每次插入都要移动位置...

Python 和 JS 有哪些相同之处

【嵌牛导读】Python 是一门运用很广泛的语言,自动化脚本、爬虫,甚至在深度学习领域也都有 Python 的身影。作为一名前端开发者,也了解 ES6 中的很多特性借鉴自 Python...