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

转载于:https://my.oschina.net/jastme/blog/483424

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值