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

yipeiwu_com5年前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程序设计有所帮助。

相关文章

python使用PIL给图片添加文字生成海报示例

python使用PIL给图片添加文字生成海报示例

前言 曾经,我也算半个所谓的文学青年。大学前两年大部分时间泡在图书馆看各种文学类的书。 那时的我,对于未来有很多遐想:写小说、写时评、写诗歌... 总而言之,就是成为一个文字工作者 现...

初学python数组的处理代码

初学python,小缘缘出了几道题: 有一 list a = [1, 2, 3, 4, 5, 6] 请将 a 依 0, 1 1, 2 2, 3 3, 4 4, 5 5, 6 打印输出,...

python绘制漏斗图步骤详解

python绘制漏斗图步骤详解

pyecharts中的Funnel函数可以绘制漏斗图,自动根据数据大小生成由大到小自上而下排列的一个漏斗样的图形。 1、导入Funnel模块。 from pyecharts import...

网易有道2017内推编程题 洗牌(python)

本文实例为大家分享了网易有道2017内推编程题:洗牌,供大家参考,具体内容如下 ''' [编程题] 洗牌 时间限制:1秒 空间限制:32768K 洗牌在生活中十分常见,现在需要写一个程...

python3.7环境下安装Anaconda的教程图解

python3.7环境下安装Anaconda的教程图解

下载Anaconda安装包 官网下载或是在清华大学镜像站下载,我安装的是下面这个版本:   安装过程 配置环境 将anaconda的scripts文件夹路径添...