Python装饰器用法实例分析

yipeiwu_com5年前Python基础

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

无参数的装饰器

#coding=utf-8
def log(func):
  def wrapper():
    print 'before calling ',func.__name__
    func()
    print 'end calling ',func.__name__
  return wrapper
@log
def hello():
  print 'hello'
@log
def hello2(name):
  print 'hello',name
if __name__=='__main__':
  hello()

运行结果:

before calling  hello
hello
end calling  hello

带参数的装饰器:

#coding=utf-8
def log(func):
  def wrapper(name):
    print 'before calling ',func.__name__
    func(name)
    print 'end calling ',func.__name__
  return wrapper
@log
def hello(name):
  print 'hello',name
@log
def hello2(name):
  print 'hello',name
if __name__=='__main__':
  hello('haha')

运行结果:

before calling  hello
hello haha
end calling  hello

多个参数的时候:

#coding=utf-8
def log(func):
  '''
  *无名字的参数
  **有名字的参数
  :param func:
  :return:
  '''
  def wrapper(*args,**kvargs):
    print 'before calling ',func.__name__
    print 'args',args,'kvargs',kvargs
    func(*args,**kvargs)
    print 'end calling ',func.__name__
  return wrapper
@log
def hello(name,age):
  print 'hello',name,age
@log
def hello2(name):
  print 'hello',name
if __name__=='__main__':
  hello('haha',2)
  hello(name='hehe',age=3)

输出:

end calling  hello
before calling  hello
args () kvargs {'age': 3, 'name': 'hehe'}
hello hehe 3
end calling  hello

装饰器里带参数的情况

本质就是嵌套函数

#coding=utf-8
def log(level,*args,**kvargs):
  def inner(func):
    def wrapper(*args,**kvargs):
      print level,'before calling ',func.__name__
      print level,'args',args,'kvargs',kvargs
      func(*args,**kvargs)
      print level,'end calling ',func.__name__
    return wrapper
  return inner
@log(level='INFO')
def hello(name,age):
  print 'hello',name,age
@log
def hello2(name):
  print 'hello',name
if __name__=='__main__':
  hello('haha',2)

运行输出:

INFO before calling  hello
INFO args ('haha', 2) kvargs {}
hello haha 2
INFO end calling  hello

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

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

相关文章

Pytorch 神经网络—自定义数据集上实现教程

Pytorch 神经网络—自定义数据集上实现教程

第一步、导入需要的包 import os import scipy.io as sio import numpy as np import torch import torch.nn...

python实现beta分布概率密度函数的方法

python实现beta分布概率密度函数的方法

如下所示: beta分布的最大特点是其多样性, 从下图可以看出, beta分布具有各种形态, 有U形, 类似正态分布的形状, 类似uniform分布的形状等, 正式这一特质使beta...

详解Django解决ajax跨域访问问题

详解Django解决ajax跨域访问问题

这篇文章主要给大家介绍了关于Django跨域请求问题解决的相关资料,文中介绍的实现方法包括:使用django-cors-headers全局控制、使用JsonP,只能用于Get方法以及在v...

Python+Turtle动态绘制一棵树实例分享

Python+Turtle动态绘制一棵树实例分享

本文实例主要是对turtle的使用,实现Python+turtle动态绘制一棵树的实例,具体代码: # drawtree.py from turtle import Turtle...

python 文件操作删除某行的实例

使用continue跳过本次写循环就可以了 #文本内容 Yesterday when I was young 昨日当我年少轻狂 The tasting of life was swe...