手机
当前位置:查字典教程网 >脚本专栏 >python >python利用装饰器进行运算的实例分析
python利用装饰器进行运算的实例分析
摘要:今天想用python的装饰器做一个运算,代码如下>>>defmu(x):def_mu(*args,**kwargs):returnx*xre...

今天想用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利用装饰器进行运算的实例分析】相关文章:

python实现多线程采集的2个代码例子

Python实现多线程下载文件的代码实例

python求素数示例分享

python的正则表达式re模块的常用方法

python的迭代器与生成器实例详解

Python实现的几个常用排序算法实例

python单链表实现代码实例

python创建和使用字典实例详解

python操作摄像头截图实现远程监控的例子

wxpython中利用线程防止假死的实现方法

精品推荐
分类导航