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 实现简单的FTP程序

python 实现简单的FTP程序

FTP即文件传输协议;它基于客户机-服务器模型体系结构,应用广泛。它有两个通道:一个命令通道和一个数据通道。命令通道用于控制通信,数据通道用于文件的实际传输。使用FTP可以做很多事情,比...

python使用scrapy解析js示例

复制代码 代码如下:from selenium import selenium class MySpider(CrawlSpider):    name =...

使用python对excle和json互相转换的示例

python 版本:2.7 只是读取excel的话可以直接使用xlrd 1、excle to json 代码如下 # -*-coding:utf8 -*- import xlrd f...

Django接收post前端返回的json格式数据代码实现

post接收字符串 def subscription(request): msg = request.POST.get('msg') # tel_no = request....

Python实现base64编码的图片保存到本地功能示例

Python实现base64编码的图片保存到本地功能示例

本文实例讲述了Python实现base64编码的图片保存到本地功能。分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- #!python3 import...