理解python的decorator,pythondecorator,假定有这么一个需求,通过
理解python的decorator,pythondecorator,假定有这么一个需求,通过
假定有这么一个需求,通过给方法say()
添加两个decorator方法@makebold
和@makeitalic
,这样可以使say()的返回结果自动添上b标签和i标签。
@makebold@makeitalicdef say(): return "Hello"
上面的代码应该返回:
<b><i>Hello</i></b>
下面是实现代码:
def makebold(fn): def wrapped(): return "<b>" + fn() + "</b>" return wrappeddef makeitalic(fn): def wrapped(): return "<i>" + fn() + "</i>" return wrapped@makebold@makeitalicdef hello(): return "hello world"print hello()
可以看到makebold
和makeitalic
方法都对原函数做了修改,在原函数的返回结果上添加了对应标签。
不得不承认python是一个非常干练的语言,设计模式中的修饰模式在python中内置实现了。
相关内容
- python调用外部命令获得执行结果,python外部命令,要在
- python正则表达式re模块使用总结,python正则表达式,一、
- Pythonic的Redis库 OOREDIS 介绍,pythonicredis,用Redis的朋友们
- python使用pgsql连接postgresql,pgsqlpostgresql,决定使用pytho
- python读写excel例子,python读写excel,你知道吗?python也
- python中清除html标签,pythonhtml标签,如下代码实现清除
- python手动释放 内存的问题, python explicitly free memory.,
- python使用unittest进行单元测试,pythonunittest,simptest.py#
- python时间和时间戳之间的相互转换,python时间相互转换
- python filter使用示例,pythonfilter示例,列表用得比较多,
评论关闭