深入浅出分析Python装饰器用法


Posted in Python onJuly 28, 2017

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

用类作为装饰器

示例一

最初代码:

class bol(object):
 def __init__(self, func):
  self.func = func
 def __call__(self):
  return "<b>{}</b>".format(self.func())
class ita(object):
 def __init__(self, func):
  self.func = func
 def __call__(self):
  return "<i>{}</i>".format(self.func())
@bol
@ita
def sayhi():
 return 'hi'

改进一:

class sty(object):
 def __init__(self, tag):
  self.tag = tag
 def __call__(self, f):
  def wraper():
   return "<{tag}>{res}</{tag}>".format(res=f(), tag=self.tag)
  return wraper
@sty('b')
@sty('i')
def sayhi():
 return 'hi'

改进二:

class sty(object):
 def __init__(self, *tags):
  self.tags = tags
 def __call__(self, f):
  def wraper():
   n = len(self.tags)
   return "{0}{1}{2}".format(('<{}>'*n).format(*self.tags), f(), ('</{}>'*n).format(*reversed(self.tags)))
  return wraper
@sty('b', 'i')
def sayhi():
 return 'hi'
print(sayhi())

改进三:

class sty(object):
 def __init__(self, *tags):
  self.tags = tags
 def __call__(self, f):
  def wraper(*args, **kwargs):
   n = len(self.tags)
   return "{0}{1}{2}".format(('<{}>'*n).format(*self.tags), f(*args, **kwargs), ('</{}>'*n).format(*reversed(self.tags)))
  return wraper
@sty('b', 'i')
def say(word='Hi'):
 return word
print(say())
print(say('Hello'))

示例二

最初代码:

import threading
import time
class DecoratorClass(object):
  def __init__(self):
    self.thread = None
  def __call__(self, func, *args, **kwargs):
    def wrapped_func(*args, **kwargs):
      curr_thread = threading.currentThread().getName()
      self.thread = curr_thread
      print('\nthread name before running func:', self.thread)
      ret_val = func()
      print('\nthread name after running func:', self.thread)
      return ret_val
    return wrapped_func
@DecoratorClass()
def decorated_with_class():
  print('running decorated w class')
  time.sleep(1)
  return
threads = []
for i in range(5):
  t = threading.Thread(target=decorated_with_class)
  threads.append(t)
  t.setDaemon(True)  # 守护
  t.start()

改进:进程锁

import threading
import time
class DecoratorClass(object):
  def __init__(self):
    self.thread = None
    self.lock = threading.Lock()
  def __call__(self, func, *args, **kwargs):
    def wrapped_func(*args, **kwargs):
      self.lock.acquire()
      curr_thread = threading.currentThread().getName()
      self.thread = curr_thread
      print('thread name before running func:', self.thread)
      ret_val = func()
      print('\nthread name after running func:', self.thread)
      self.lock.release()
      return ret_val
    return wrapped_func
@DecoratorClass()
def decorated_with_class():
  print('Let me sleep 1 second...')
  time.sleep(1)
  return
threads = []
for i in range(5):
  t = threading.Thread(target=decorated_with_class)
  threads.append(t)
  t.start()

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

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

Python 相关文章推荐
python中的一些类型转换函数小结
Feb 10 Python
Python中多线程及程序锁浅析
Jan 21 Python
python类中super()和__init__()的区别
Oct 18 Python
详解python的数字类型变量与其方法
Nov 20 Python
Python实现基于二叉树存储结构的堆排序算法示例
Dec 08 Python
用十张图详解TensorFlow数据读取机制(附代码)
Feb 06 Python
Selenium定时刷新网页的实现代码
Oct 31 Python
Python通过TensorFlow卷积神经网络实现猫狗识别
Mar 14 Python
详解如何从TensorFlow的mnist数据集导出手写体数字图片
Aug 05 Python
pytorch中使用cuda扩展的实现示例
Feb 12 Python
Django 用户认证Auth组件的使用
Nov 30 Python
浅析python字符串前加r、f、u、l 的区别
Jan 24 Python
分享一个可以生成各种进制格式IP的小工具实例代码
Jul 28 #Python
Python使用sorted排序的方法小结
Jul 28 #Python
python发送邮件实例分享
Jul 28 #Python
Python分治法定义与应用实例详解
Jul 28 #Python
Python更新数据库脚本两种方法及对比介绍
Jul 27 #Python
Python判断文件或文件夹是否存在的三种方法
Jul 27 #Python
Python开发SQLite3数据库相关操作详解【连接,查询,插入,更新,删除,关闭等】
Jul 27 #Python
You might like
PHP操作xml代码
2010/06/17 PHP
PHP实现图片批量打包下载功能
2017/03/01 PHP
PHP date()格式MySQL中插入datetime方法
2019/01/29 PHP
css3实现背景模糊的三种方式
2021/03/09 HTML / CSS
javascript中强制执行toString()具体实现
2013/04/27 Javascript
Jquery 的outerHeight方法使用介绍
2013/09/11 Javascript
JavaScript的类型、值和变量小结
2015/07/09 Javascript
JavaScript判断DIV内容是否为空的方法
2016/01/29 Javascript
js基于cookie记录来宾姓名的方法
2016/07/19 Javascript
Javascript typeof与instanceof的区别
2016/10/18 Javascript
最好用的Bootstrap fileinput.js文件上传组件
2016/12/12 Javascript
Angular 1.x个人使用的经验小结
2017/07/19 Javascript
jQuery实现验证表单密码一致性及正则表达式验证邮箱、手机号的方法
2017/12/05 jQuery
js中this的指向问题归纳总结
2018/11/28 Javascript
vue计算属性computed的使用方法示例
2019/03/13 Javascript
Vue项目总结之webpack常规打包优化方案
2019/06/06 Javascript
vue el-table实现自定义表头
2019/12/11 Javascript
记一次vue跨域的解决
2020/10/21 Javascript
微信小程序实现首页弹出广告
2020/12/03 Javascript
[01:55]TI9显影之尘系列 - Evil Geniuses
2019/08/22 DOTA
python遍历文件夹并删除特定格式文件的示例
2014/03/05 Python
python中readline判断文件读取结束的方法
2014/11/08 Python
python中的全局变量用法分析
2015/06/09 Python
Python 专题一 函数的基础知识
2017/03/16 Python
Python实现完整的事务操作示例
2017/06/20 Python
Pandas GroupBy对象 索引与迭代方法
2018/11/16 Python
厨房管理计划书
2014/04/27 职场文书
2014年教师业务学习材料
2014/05/12 职场文书
商务英语专业求职信
2014/06/26 职场文书
孝敬父母的活动方案
2014/08/28 职场文书
房屋租赁合同补充协议
2014/10/11 职场文书
幼儿园老师新年寄语2015
2014/12/08 职场文书
Python基础学习之奇异的GUI对话框
2021/05/27 Python
mybatis 解决从列名到属性名的自动映射失败问题
2021/06/30 Java/Android
Python 多线程处理任务实例
2021/11/07 Python
Python字符串格式化方式
2022/04/07 Python