Python 装饰器原理、定义与用法详解


Posted in Python onDecember 07, 2019

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

Python 装饰器

一、何为装饰器

1、在函数中定义函数

在函数中定义另外的函数,就是说可以创建嵌套的函数,例子如下

def sayHi(name="hjj2"):
 print 'inside sayHi() func'
 def greet():
  return 'inside greet() func'
 print(greet())
sayHi()
#output
#  inside sayHi() func
#  inside greet() func

2、将函数作为参数传给另外一个函数,装饰器原型

def sayHi():
 return 'hi hjj2'
def doSthBeforeSayHi(func):
 print 'before sayHi func'
 print(func())
doSthBeforeSayHi(sayHi)
#output
#  before sayHi func
#  hi hjj2

3、实现一个装饰器

在第二步中,我们已经基本探究到装饰器的原理了,python装饰器做的事就是通过封装一个函数并且用这样或那样的方式来修改它的行为。不带@的初步示例如下:

def new_decorator(func):
  def wrapDecorator():
   print 'before func'
   func()
   print 'after func'
  return wrapDecorator
def func_require_decorator():
  print 'a func need decorator'
func_require_decorator()
#ouput: a func need decorator
func_require_decorator = new_decorator(func_require_decorator)
func_require_decorator()
#ouput:
#  before func
#  a func need decorator
#  after func

使用@来运行装饰器

@new_decorator
func_require_decorator()
#ouput:
#  before func
#  a func need decorator
#  after func

这里我们可以看到,这两个例子的运行结果是一样的。所以我们能想象得到@new_decorator的作用就是

func_require_decorator = new_decorator(func_require_decorator)

我们继续优化这个装饰器,现在我们有一个问题就是,如果我们想要通过print(func_require_decorator.__name__)就会报错# Output: wrapTheFunction。这样就需要借助python提供的functools.wraps来解决了

@wraps接受一个函数来进行装饰,并加入了复制函数名称、注释文档、参数列表等等的功能。这可以让我们在装饰器里面访问在装饰之前的函数的属性。

from functools import wraps
def new_decorator(func):
  @wraps(func)
  def wrapDecorator():
   print 'before func'
   func()
   print 'after func'
  return wrapDecorator
def func_require_decorator():
  print 'a func need decorator'
@new_decorator
func_require_decorator()
print(func_require_decorator.__name__)
#ouput: func_require_decorator

二、使用场景

1、授权,大体例子

from functools import wraps
def requires_auth(f):
  @wraps(f)
  def decorated(*args, **kwargs):
    auth = request.authorization
    if not auth or not check_auth(auth.username, auth.password):
      authenticate()
    return f(*args, **kwargs)
  return decorated

2、日志:

from functools import wraps
def logit(logfile='out.log'):
  def logging_decorator(func):
    @wraps(func)
    def wrapped_function(*args,**kwargs):
      log_string = func.__name__+"was called"
      print(log_string)
      with open(logfile,'a') as opened_file:
        opened_file.write(log_string+'\n')
      return func(*args,**kwargs)
    return wrapped_function
  return logging_decorator
@logit()
def func1():
  pass
func1()

3、其他如flask中的@app.route()

三、装饰器类

1、将上面的日志装饰器变为类的初步模型如下

from functools import wraps
class logit(object):
  def __init__(self, logfile='out.log'):
    self.logfile = logfile
  def __call__(self, func):
    @wraps(func)
    def wrapped_function(*args, **kwargs):
      log_string = func.__name__ + "was called"
      print(log_string)
      # 打开logfile并写入
      with open(self.logfile, 'a') as open_file:
        # 将日志写到指定文件
        open_file.write(log_string + '\n')
      # 发送一个通知
      self.notify()
      return func(*args, **kwargs)
    return wrapped_function
  def notify(self):
    pass
@logit()
def myfunc1():
  pass
class email_logit(logit):
  '''
  实现在函数调用时发送email
  '''
  def __init__(self, email='admin@xxx.com', *args, **kwargs):
    self.email = email
    super(email_logit, self).__init__(*args, **kwargs)
  def notify(self):
    '''
    发送邮件通知
    '''
    pass

通过这种方式,我们可以定义我们在自己的需求,减少代码的冗余,提高复用率。

至此,关于装饰器的探索就结束啦。

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

Python 相关文章推荐
Python根据区号生成手机号码的方法
Jul 08 Python
Tensorflow实现卷积神经网络用于人脸关键点识别
Mar 05 Python
django中的HTML控件及参数传递方法
Mar 20 Python
Python可变参数*args和**kwargs用法实例小结
Apr 27 Python
Python通过paramiko远程下载Linux服务器上的文件实例
Dec 27 Python
Django如何防止定时任务并发浅析
May 14 Python
Python基于机器学习方法实现的电影推荐系统实例详解
Jun 25 Python
Tensorflow:转置函数 transpose的使用详解
Feb 11 Python
Pycharm2020.1安装无法启动问题即设置中文插件的方法
Aug 07 Python
PyCharm 光标变成黑块的解决方式
Feb 06 Python
python爬虫之爬取笔趣阁小说
Apr 22 Python
Python爬虫框架之Scrapy中Spider的用法
Jun 28 Python
Python Pandas 转换unix时间戳方式
Dec 07 #Python
Pandas-Cookbook 时间戳处理方式
Dec 07 #Python
Python数据可视化:饼状图的实例讲解
Dec 07 #Python
Python数据可视化:幂律分布实例详解
Dec 07 #Python
Python数据可视化:泊松分布详解
Dec 07 #Python
python-numpy-指数分布实例详解
Dec 07 #Python
Python Sympy计算梯度、散度和旋度的实例
Dec 06 #Python
You might like
Smarty结合Ajax实现无刷新留言本实例
2007/01/02 PHP
PHP has encountered a Stack overflow问题解决方法
2014/11/03 PHP
php中foreach结合curl实现多线程的方法分析
2016/09/22 PHP
Laravel5.* 打印出执行的sql语句的方法
2017/07/24 PHP
JavaScript中的prototype.bind()方法介绍
2014/04/04 Javascript
javascript实现控制文字大中小显示
2015/04/28 Javascript
详解WordPress开发中get_current_screen()函数的使用
2016/01/11 Javascript
jQuery实现底部浮动窗口效果
2016/09/07 Javascript
基于Javascript实现文件实时加载进度的方法
2016/10/12 Javascript
详谈angularjs中路由页面强制更新的问题
2017/04/24 Javascript
jQuery实现的表格前端排序功能示例
2017/09/18 jQuery
微信小程序实现折叠展开效果
2018/07/19 Javascript
引入外部js脚本加载慢与页面白屏问题的解决
2018/12/10 Javascript
angular 实现同步验证器跨字段验证的方法
2019/04/11 Javascript
JS实现可控制的进度条
2020/03/25 Javascript
JavaScript实现移动端弹窗后禁止滚动
2020/05/25 Javascript
vue移动端写的拖拽功能示例代码
2020/09/09 Javascript
JavaScript实现网页跨年倒计时
2020/12/02 Javascript
python中将阿拉伯数字转换成中文的实现代码
2011/05/19 Python
Python OS模块常用函数说明
2015/05/23 Python
python递归删除指定目录及其所有内容的方法
2017/01/13 Python
Python线程创建和终止实例代码
2018/01/20 Python
Django REST framework 视图和路由详解
2019/07/19 Python
Python实现验证码识别
2020/06/15 Python
浅谈Python3中print函数的换行
2020/08/05 Python
多重CSS背景动画实现方法示例
2014/04/04 HTML / CSS
如何使用css3实现一个类在线直播的队列动画的示例代码
2020/06/17 HTML / CSS
Snapfish英国:在线照片打印和个性化照片礼品
2017/01/13 全球购物
expedia比利时:预订航班+酒店并省钱
2018/07/13 全球购物
Under Armour安德玛德国官网:美国高端运动科技品牌
2019/03/09 全球购物
Puccini乌克兰:购买行李箱、女士手袋网上商店
2020/08/06 全球购物
英语翻译系毕业生求职信
2013/09/29 职场文书
简历上的自我评价怎么写
2014/01/28 职场文书
讲座主持词
2014/03/20 职场文书
寝室长工作失责检讨书
2014/10/06 职场文书
习近平在党的群众路线教育实践活动总结大会上的讲话全文
2014/10/25 职场文书