python装饰器传递参数_在python中将参数传递给装饰器

1586010002-jmsa.png

Why is this decorator with a parameter not working?

def decAny( f0 ):

def wrapper( s0 ):

return "<%s> %s %s>" % ( any, f0(), any )

return wrapper

@decAny( 'xxx' )

def test2():

return 'test1XML'

print( test2() )

always gives me an error saying "str is not callable"

it is trying to execute the return string inside the wrapper()

instead of processing it and return the result string

解决方案

Decorators are functions that return functions. When "passing a parameter to the decorator" what you are actually doing is calling a function that returns a decorator. So decAny() should be a function that returns a function that returns a function.

It would look something like this:

import functools

def decAny(tag):

def dec(f0):

@functools.wraps(f0)

def wrapper(*args, **kwargs):

return "<%s> %s %s>" % (tag, f0(*args, **kwargs), tag)

return wrapper

return dec

@decAny( 'xxx' )

def test2():

return 'test1XML'

Example:

>>> print(test2())

test1XML

Note that in addition to fixing the specific problem you were hitting I also improved your code a bit by adding *args and **kwargs as arguments to the wrapped function and passing them on to the f0 call inside of the decorator. This makes it so you can decorate a function that accepts any number of positional or named arguments and it will still work correctly.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值