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变量不能以数字打头详解

在编写python函数时,无意中发现一个问题:python中的变量不能以数字打头,以下函数中定义了一个变量3_num_varchar,执行时报错。 函数如下: def databas...

Python实现模拟时钟代码推荐

Python实现模拟时钟代码推荐 # coding=utf8 import sys, pygame, math, random from pygame.locals import *...

python flask web服务实现更换默认端口和IP的方法

flask web后台启动后会发现默认是 localhost 127.0.0.1:5000 如果需要修改,方便调试发布 可以采用以下方式运行 from flask import Fl...

python中eval与int的区别浅析

python中eval和int的区别是什么?下面给大家介绍一下: 1.eval()函数 eval(<字符串>)能够以Python表达式的方式解析并执行字符串,并将返回结果输出...

Python 文件操作技巧(File operation) 实例代码分析

常用的module是 os ,os.path 和shutil,所以要先引入他们. python遍历文件夹和文件 这个也许是最常用的功能,如下: 复制代码 代...