gpt4 book ai didi

Python装饰器模式定义与用法分析

转载 作者:qq735679552 更新时间:2022-09-27 22:32:09 31 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章Python装饰器模式定义与用法分析由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

本文实例讲述了Python装饰器模式定义与用法。分享给大家供大家参考,具体如下:

装饰器模式定义:动态地给一个对象添加一些额外的职责.

在Python中Decorator mode可以按照像其它编程语言如C++, Java等的样子来实现,但是Python在应用装饰概念方面的能力上远不止于此,Python提供了一个语法和一个编程特性来加强这方面的功能.

首先需要了解一下Python中闭包的概念:如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(closure).

Python装饰器模式定义与用法分析

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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> 。

Python装饰器模式定义与用法分析

?
1
2
3
4
5
6
7
8
9
10
11
12
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]. 。

关于闭包学习可参考:http://www.zzvips.com/article/103444.html 。

希望本文所述对大家Python程序设计有所帮助.

原文链接:https://www.cnblogs.com/zxlovenet/p/4042898.html 。

最后此篇关于Python装饰器模式定义与用法分析的文章就讲到这里了,如果你想了解更多关于Python装饰器模式定义与用法分析的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com