服务器之家

服务器之家 > 正文

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

时间:2020-11-29 00:12     来源/作者:罗兵

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

用类作为装饰器

示例一

最初代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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'

改进一:

?
1
2
3
4
5
6
7
8
9
10
11
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'

改进二:

?
1
2
3
4
5
6
7
8
9
10
11
12
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())

改进三:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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'))

示例二

最初代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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()

改进:进程锁

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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程序设计有所帮助。

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
电视剧《琉璃》全集在线观看 琉璃美人煞1-59集免费观看地址
电视剧《琉璃》全集在线观看 琉璃美人煞1-59集免费观看地址 2020-08-12
最新idea2020注册码永久激活(激活到2100年)
最新idea2020注册码永久激活(激活到2100年) 2020-07-29
返回顶部