Python装饰器用法示例小结

yipeiwu_com6年前Python基础

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

下面的程序示例了python装饰器的使用:

示例一:

def outer(fun):
  print fun
  def wrapper(arg):
    result=fun(arg)
    print 'over!'
    return result
  return wrapper
@outer
def func1(arg):
  print 'func1',arg
  return 'very good!'
response=func1('python')
print response
print func1

运行结果:

<function func1 at 0x02A67D70>
func1 python
over!
very good!
<function wrapper at 0x02A67CF0>

示例二:

#!/usr/bin/env python
#coding:utf-8
def Filter(before_func,after_func):
  print before_func
  print after_func
  def outer(main_func):
    print main_func
    def wrapper(request,kargs):
      before_result=before_func(request,kargs)
      if(before_result!=None):
        return before_result;
      main_result=main_func(request,kargs)
      if(main_result!=None):
        return main_result;
      after_result=after_func(request,kargs)
      if(after_result!=None):
        return after_result;
    return wrapper
  return outer
def before(request,kargs):
  print request,kargs,'之前!'
def after(request,kargs):
  print request,kargs,'之后!'
@Filter(before,after)
def main(request,kargs):
  print request,kargs
main('hello','python')
print main

运行结果:

<function before at 0x02AC7BF0>
<function after at 0x02AC7C30>
<function main at 0x02AC7CF0>
hello python 之前!
hello python
hello python 之后!
<function wrapper at 0x02AC7D30>

我们可以加上很多断点,在Debug模式下运行,查看程序一步一步的运行轨迹。。。

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

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

相关文章

Django的URLconf中使用缺省视图参数的方法

一个方便的特性是你可以给一个视图指定默认的参数。 这样,当没有给这个参数赋值的时候将会使用默认的值。 例子: # urls.py from django.conf.urls.def...

教女朋友学Python(一)运行环境搭建 原创

教女朋友学Python(一)运行环境搭建 原创

下班比较早,吃了饭没什么事,就和女朋友一起研究了Python。 编程语言有很多,为什么选择它呢?因为它火吧,没什么好解释的,下面开始第一步,环境搭建。网上的教程实在太多,各种系统的各种版...

Python+matplotlib实现华丽的文本框演示代码

Python+matplotlib实现华丽的文本框演示代码

华丽的文本框演示 首先看看演示结果: 实现代码 import matplotlib.pyplot as plt plt.text(0.8, 0.5, "python", size...

python 多维高斯分布数据生成方式

python 多维高斯分布数据生成方式

我就废话不多说了,直接上代码吧! import numpy as np import matplotlib.pyplot as plt def gen_clusters():...

python ctypes库2_指定参数类型和返回类型详解

python函数的参数类型和返回类型默认为int。 如果需要传递一个float值给dll,那么需要指定参数的类型。 如果需要返回一个flaot值到python中,那么需要指定返回数据的类...