python利用装饰器进行运算的实例分析
2015-08-04 00:00
786 查看
今天想用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实现字典的key和values的交换
- 使用python加密自己的密码
- python利用datetime模块计算时间差
- 合并百度影音的离线数据( with python 2.3)
- Python利用ansible分发处理任务
- 解决Python传递中文参数的问题
- python删除列表内容
- python函数局部变量用法实例分析
- 将Python代码打包为jar软件的简单方法
- Python简明入门教程
- python函数形参用法实例分析
- Python中return语句用法实例分析
- pyenv+virtualenv创建多版本隔离python环境
- 创建Flask开发环境
- Python导入自定义包或模块
- python爬虫(五)--爬虫程序的开始
- Python String和PyQt QString的区别(转)
- 惊艳发现VS工具python项目Search Paths的应用
- 树莓派用Python写几个简单程序3_UART_BT-HM10
- Python进阶 函数式编程和面向对象编程等