Python decorator * 代码实例解析
作者:西城老李 时间:2022-04-07 11:03:47
这个decorator是什么意思呢?
很简单,它接受一个log的参数,即传入logger对象。然后它会先把函数名打印出来,接下来,会利用enumerate函数,将args、kwargs的任意参数给展开,并按顺序输出。最后,它再将func以这些参数包装回去,继续进行函数的执行和结果返回。
例1 最简单
def get_text(name):
return "hello, {0}".format(name)
def p_decorate(func):
def func_wrapper(name):
return "<p>{0}</p>".format(func(name))
return func_wrapper
my_get_text = p_decorate(get_text)
print(my_get_text("zhangsan"))
例2 参数通用化
def p_decorate(func):
def func_wrapper(*args, **kwargs):
return "<p>{0}</p>".format(func(*args, **kwargs))
return func_wrapper
class Person(object):
def __init__(self):
self.name = "Neng"
self.family = "Xiong"
@p_decorate
def get_fullname(self):
return self.name+" "+self.family
my_person = Person()
print(my_person.get_fullname())
例3 根据参数,实现动态 *
def tags(tag_name):
def tags_decorator(func):
def func_wrapper(*args, **kargs):
return "<{0}>{1}</{0}>".format(tag_name, func(*args, **kargs))
return func_wrapper
return tags_decorator
@tags("div")
@tags("p")
@tags("strong")
def get_text(name):
return "hello, "+name
print(get_text("zhangsan"))
来源:https://www.cnblogs.com/lxgbky/p/12627092.html
标签:Python,decorator, ,
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
JS中getElementsByClassName与classList兼容性问题解决方案分析
2023-08-25 05:39:06
浅析SQL Server与Oracle数据库的区别
2007-10-31 11:39:00
JS+ASP实现无刷新新闻列表方法
2007-08-22 12:44:00
MySQL UPDATE delete 语句的速度
2008-03-12 12:22:00
准备SQL Server 2008透明数据加密
2009-01-22 14:18:00
Python遍历文件夹和读写文件的实现代码
2023-07-28 12:13:10
![](https://img.aspxhome.com/file/2023/4/60514_0s.jpg)
用FrongPage设计网页花样
2008-09-17 10:47:00
PHP实现统计代码行数小工具
2023-11-15 18:53:20
德国ebay购头记
2009-04-29 11:10:00
![](https://img.aspxhome.com/file/UploadPic/20094/29/01-96s.jpg)
ExtJS 开发总结
2009-04-28 13:05:00
![](https://img.aspxhome.com/file/UploadPic/20094/28/extanim64_3-91s.gif)
CSS pointer-events下层元素被点击
2010-04-11 22:31:00
PHP bin2hex()函数基础实例讲解
2023-06-12 16:30:44
![](https://img.aspxhome.com/file/2023/7/55397_0s.png)
一个不错的网页拾色器
2007-09-30 19:45:00
![](https://img.aspxhome.com/file/UploadPic/20079/30/2007930201019921s.jpg)
用户研究角度看设计(1)“复制链接”的故事
2008-12-26 17:48:00
介绍Python中几个常用的类方法
2023-02-10 09:17:49
用ASP实现远程批量文件改名
2007-09-12 12:23:00
完美解决ARIMA模型中plot_acf画不出图的问题
2023-07-13 14:17:34
![](https://img.aspxhome.com/file/2023/1/61761_0s.jpg)
MySQL Create Database 创建数据库
2011-09-10 16:04:51
XMLHTTPRequest的属性和方法简介
2007-12-18 18:42:00
python 列表元素左右循环移动 的多种解决方案
2023-06-15 06:21:45
![](https://img.aspxhome.com/file/2023/9/59649_0s.jpg)