Python decorator 2: 类
2016-04-14 19:13
483 查看
class myDecorator(object): def __init__(self, fn): print "inside myDecorator.__init__()" self.fn = fn def __call__(self): self.fn() print "inside myDecorator.__call__()" @myDecorator def aFunction(): print "inside aFunction()" print "Finished decorating aFunction()" aFunction() # 输出: # inside myDecorator.__init__() # Finished decorating aFunction() # inside aFunction() # inside myDecorator.__call__()
上面这个示例展示了,用类的方式声明一个decorator。我们可以看到这个类中有两个成员:
1)一个是__init__(),这个方法是在我们给某个函数decorator时被调用,所以,需要有一个fn的参数,也就是被decorator的函数。
2)一个是__call__(),这个方法是在我们调用被decorator函数时被调用的。
上面输出可以看到整个程序的执行顺序。
__init()__可以看成函数式decorator中外层函数
__call()__可以看成函数式decorator中的内层函数
上面的class可以看成以下函数形式
def myDecorator(fn): print ("inside myDecorator.__init__()") def newDecorator(): fn(); print ("inside myDecorator.__call__()") return newDecorator
思考:
class makeHtmlTagClass(object): def __init__(self, tag, css_class=""): self._tag = tag self._css_class = " class='{0}'".format(css_class) \ if css_class !="" else "" def __call__(self, fn): def wrapped(*args, **kwargs): return "<" + self._tag + self._css_class+">" \ + fn(*args, **kwargs) + "</" + self._tag + ">" return wrapped @makeHtmlTagClass(tag="b", css_class="bold_css") @makeHtmlTagClass(tag="i", css_class="italic_css") def hello(name): return "Hello, {}".format(name) print (hello("Hao Chen"))
结果
<b class='bold_css'><i class='italic_css'>Hello, Hao Chen</i></b>
相关文章推荐
- python学习11-集合和字典
- Python MySQL(MySQLdb)
- python脚本技巧
- 【python学习】windows下安装MySQLdb
- Python 练习册 5-调整文件夹内所有图片的分辨率
- Python 练习册 4-统计文本文件中单词出现的个数
- Python 练习册 2-存储激活码到MySQL数据库
- Python 练习册 1-生成激活码
- Python 练习册 0-头像右上角添加数字
- Python实现自动存储Windows 10锁屏聚焦图片到指定文件夹
- Python将数据插入到数据库时遇到单引号插入错误的问题
- thinkpython2
- 如何在windows下安装Python的PIL库
- Python机器学习之Logistic回归
- 运维通用python脚本框架
- 用Python玩转数据第一周学习笔记のPython基础
- python(datetime、字符串转换)
- Python_学习笔记
- 运维通用python脚本框架
- python--文件处理1