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

yipeiwu_com6年前Python基础

本文实例讲述了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].

关于闭包学习可参考:/post/54498.htm

更多关于Python相关内容可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

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

相关文章

Python实现将16进制字符串转化为ascii字符的方法分析

本文实例讲述了Python实现将16进制字符串转化为ascii字符的方法。分享给大家供大家参考,具体如下: 字符串456e633064316e675f31735f66336e,通过Pyt...

Python 从列表中取值和取索引的方法

如下所示: name_list["zhangsan","lisi","wangwu"] #1.取值 print(name_list[0]) print(name_list[1])...

Python中使用hashlib模块处理算法的教程

Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等。 什么是摘要算法呢?摘要算法又称哈希算法、散列算法。它通过一个函数,把任意长度的数据转换为一个长度固定的数据串(...

Python反射用法实例简析

本文实例讲述了Python反射用法。分享给大家供大家参考,具体如下: class Person: def __init__(self): self.name = "zjg...

Python使用chardet判断字符编码

本文实例讲述了Python使用chardet判断字符编码的方法。分享给大家供大家参考。具体分析如下: Python中chardet 用来实现字符串/文件编码检测模板 1、chardet下...