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

 更新时间:2017年07月28日 10:12:31   作者:罗兵  
这篇文章主要介绍了Python装饰器用法,结合实例形式对比分析了Python装饰器的定义与使用技巧,需要的朋友可以参考下

本文实例讲述了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程序设计有所帮助。

相关文章

  • 教你实现Ubuntu安装Python

    教你实现Ubuntu安装Python

    这篇文章主要为大家介绍了Ubuntu安装Python的实现过程详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-06-06
  • python使用技巧-文件读写

    python使用技巧-文件读写

    这篇文章主要介绍了python使用技巧-文件读写,Python提供了非常方便的文件读写功能,其中open是读写文件的第一步,通过open读写文件的方式和把大象装冰箱是一样的,下面我们就来具体介绍该内容,需要的小伙伴可以参考一下
    2022-02-02
  • Python编译结果之code对象与pyc文件详解

    Python编译结果之code对象与pyc文件详解

    今天小编就为大家分享一篇对Python编译结果之code对象与pyc文件的详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-10-10
  • Python 手动导包的实现

    Python 手动导包的实现

    本文主要介绍了Python 手动导包的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-03-03
  • 详解opencv去除背景算法的方法比较

    详解opencv去除背景算法的方法比较

    本文主要介绍了opencv去除背景算法的方法比较,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-08-08
  • 线程和进程的区别及Python代码实例

    线程和进程的区别及Python代码实例

    这篇文章主要介绍了线程和进程的区别及Python代码实例,本文给出了一个python的脚本让一个进程中运行两个线程,需要的朋友可以参考下
    2015-02-02
  • Python文本预处理学习指南

    Python文本预处理学习指南

    文本预处理是指在进行自然语言处理(NLP)任务之前,对原始文本数据进行清洗、转换和标准化的过程,本文主要为大家介绍了文本预处理的使用,需要的可以参考下
    2023-07-07
  • 浅谈keras中Dropout在预测过程中是否仍要起作用

    浅谈keras中Dropout在预测过程中是否仍要起作用

    这篇文章主要介绍了浅谈keras中Dropout在预测过程中是否仍要起作用,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-07-07
  • Python logging日志模块使用指南

    Python logging日志模块使用指南

    Python 的 logging 模块提供了标准的日志接口,可以通过它存储各种格式的日志,日志记录提供了一组便利功能,用于简单的日志记录用法,本文就给大家简单的介绍一下Python logging日志模块使用方法,需要的朋友可以参考下
    2023-08-08
  • Python pygame绘制游戏图像

    Python pygame绘制游戏图像

    这篇文章主要介绍了Python pygame绘制游戏图像,文章围绕主题展开pygame模块完成飞机大战游戏的实战开发的案例详情,需要的朋友可以参考一下
    2022-08-08

最新评论