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

yipeiwu_com6年前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的Flask框架结合MySQL写一个内存监控程序

用Python的Flask框架结合MySQL写一个内存监控程序

这里以监控内存使用率为例,写的一个简单demo性程序,具体操作根据51reboot提供的教程写如下。 一、建库建表 创建falcon数据库: mysql> create dat...

Python序列操作之进阶篇

简介 Python 的序列(sequence)通常指一个可迭代的容器,容器中可以存放任意类型的元素。列表和元组这两种数据类型是最常被用到的序列,python内建序列有六种,除了刚刚有说过...

基于TensorFlow常量、序列以及随机值生成实例

TensorFlow 生成 常量、序列和随机值 生成常量 tf.constant()这种形式比较常见,除了这一种生成常量的方式之外,像Numpy一样,TensorFlow也提供了生成...

Linux下用Python脚本监控目录变化代码分享

#!/usr/bin/env python #coding=utf-8 import os from pyinotify import WatchManager, Notifier...

Python群发邮件实例代码

直接上代码了 复制代码 代码如下:import smtplibmsg = MIMEMultipart() #构造附件1att1 = MIMEText(open('/home/a2bgee...