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()

转载于:https://www.cnblogs.com/hhh5460/p/6720889.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值