秋天是金灿灿的丰收,秋天是沉甸甸的硕果,秋天是让人满载而归的欢笑和欣喜。
本文实例讲述了Python装饰器模式定义与用法。分享给大家供大家参考,具体如下:
装饰器模式定义:动态地给一个对象添加一些额外的职责。
在Python中Decorator mode可以按照像其它编程语言如C++, Java等的样子来实现,但是Python在应用装饰概念方面的能力上远不止于此,Python提供了一个语法和一个编程特性来加强这方面的功能。
首先需要了解一下Python中闭包的概念:如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(closure)。
def makeblod(fn):
def wrapped():
return '<b>'+fn()+'</b>'
return wrapped
def makeitalic(fn):
def wrapped():
return '<i>'+fn()+'</i>'
return wrapped
@makeblod
@makeitalic
def hello():
return 'hello world'
print hello()
运行结果:
<b><i>hello world</i></b>
def deco(arg):
def _deco(func):
def __deco():
print "before %s called [%s]." % (func.__name__, arg)
func()
print "after %s called [%s]." % (func.__name__, arg)
return __deco
return _deco
@deco("mymodule")
def myfunc():
print "myfunc() called."
myfunc()
运行结果:
before myfunc called [mymodule].
myfunc() called.
after myfunc called [mymodule].
关于闭包学习可参考:https://www.haodaima.com/article/54498.htm
希望本文所述对大家Python程序设计有所帮助。
到此这篇关于Python装饰器模式定义与用法分析就介绍到这了。方向对了,剩下的就是坚持。更多相关Python装饰器模式定义与用法分析内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!