python利用装饰器进行运算的实例分析
2019/7/13 21:00:18
本文主要是介绍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利用装饰器进行运算的实例分析的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-27使用python 将ETH账户的资产打散
- 2024-09-26Python编程基础
- 2024-09-2610 种方法写出更好的 Python 代码
- 2024-09-25Python编程基础详解
- 2024-09-25Python编程入门教程
- 2024-09-25从零开始使用Python构建LLaMA 3
- 2024-09-23Python中理解和使用树形结构的简单教程
- 2024-09-23Python 编程基础入门
- 2024-09-18初探Python股票自动化交易:入门指南
- 2024-09-18Python量化入门:轻松掌握量化分析基础与实战