深入浅出分析Python装饰器用法
作者:罗兵 时间:2022-10-25 16:49:02
本文实例讲述了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,装饰器
0
投稿
猜你喜欢
Django使用redis缓存服务器的实现代码示例
2022-12-15 09:16:28
用Python抢过年的火车票附源码
2021-11-12 00:01:42
解决在Python编辑器pycharm中程序run正常debug错误的问题
2023-09-09 09:58:39
Pandas如何对Categorical类型字段数据统计实战案例
2023-03-01 20:02:26
javascrip关于继承的小例子
2024-04-22 22:17:49
Pytorch:dtype不一致问题(expected dtype Double but got dtype Float)
2023-07-05 21:57:33
python3写的简单本地文件上传服务器实例
2023-08-23 02:50:58
说说掌握JavaScript语言的思想前提
2008-12-26 17:59:00
Python time模块时间获取和转换方法
2022-06-07 11:14:30
wxPython之解决闪烁的问题
2022-05-12 13:21:30
适合前端Vue开发童鞋的跨平台Weex的使用详解
2024-05-22 10:42:20
Python+OpenCV图像处理—— 色彩空间转换
2022-02-12 16:28:01
在Python的Flask框架下收发电子邮件的教程
2021-03-05 08:54:37
不同浏览器空格的宽度
2007-08-22 08:29:00
Python实现多态、协议和鸭子类型的代码详解
2021-03-16 19:02:35
python可视化plotly 图例(legend)设置
2021-05-17 11:17:56
解决python将xml格式文件转换成txt文件的问题(xml.etree方法)
2021-10-21 02:51:13
python logging日志模块的详解
2021-04-27 19:16:55
使用keras时input_shape的维度表示问题说明
2023-05-10 02:52:25
微信小程序 云开发模糊查询实现解析
2023-08-24 14:47:57