python利用装饰器进行运算的实例分析

yipeiwu_com5年前Python基础

今天想用python的装饰器做一个运算,代码如下

>>> def mu(x):
  def _mu(*args,**kwargs):
    return x*x
  return _mu

>>> @mu
def test(x,y):
  print '%s,%s' %(x,y)

>>> test(3,5)

Traceback (most recent call last):
 File "<pyshell#111>", line 1, in <module>
  test(3,5)
 File "<pyshell#106>", line 3, in _mu
  return x*x
TypeError: unsupported operand type(s) for *: 'function' and 'function'

原来是不能这样弄的  函数与函数是不能运算的啊!

怎么办呢?

In [1]: from functools import wraps

In [2]: def mu(x):
  ...:     @wraps(x)
  ...:     def _mu(*args,**kwargs):
  ...:             x,y=args
  ...:             return x*x
  ...:     return _mu
  ...: 

In [3]: @mu
  ...: def test(x,y):
  ...:     print '%s,%s' %(x,y)
  ...:   

In [4]: test(3,4)
Out[4]: 9

Python装饰器(decorator)在实现的时候,有一些细节需要被注意。例如,被装饰后的函数其实已经是另外一个函数了(函数名等函数属性会发生改变)

Python的functools包中提供了一个叫wraps的decorator来消除这样的副作用。写一个decorator的时候,最好在实现之前加上functools的wrap,它能保留原有函数的名称和docstring。

以上所述就是本文的 全部内容了,希望大家能够喜欢。

相关文章

Python进阶之@property动态属性的实现

Python 动态属性的概念可能会被面试问到,在项目当中也非常实用,但是在一般的编程教程中不会提到,可以进修一下。 先看一个简单的例子。创建一个 Student 类,我希望通过实例来获取...

使用go和python递归删除.ds store文件的方法

python版本:复制代码 代码如下:#!/usr/bin/env pythonimport os, sys;def walk(path):  print "cd directory:"...

Python3的高阶函数map,reduce,filter的示例详解

函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。 注意其中:map和filter返回一个惰性序列,可迭代对象,需要转化为list >&...

详解Python list 与 NumPy.ndarry 切片之间的对比

详解Python list 与 NumPy.ndarry 切片之间的区别 实例代码: # list 切片返回的是不原数据,对新数据的修改不会影响原数据 In [45]: list1...

TensorFlow实现Softmax回归模型

一、概述及完整代码 对MNIST(MixedNational Institute of Standard and Technology database)这个非常简单的机器视觉数据集,T...