Decorator(2) 7/2/18 : decorator with argument(s) !
Decorator with Argument !!
def decorator(argument): def shout(wrapped): # this is the real decorator !! @wraps(wrapped) def inner(*args, **kargs): print('Before {}'.format(argument)) ret = wrapped(*args,**kargs) print('After {}'.format(argument)) return ret return inner return shout
@decorator('Chrisma ! ') def myfunc(): print('Buy a gift!') myfunc() #++ output:
# Before Chrisma !
# Buy a gift!
# After Chrisma !
Also the argument can be anything, here I attempt to print out
'Before' and 'After' several times and the input argument
is the number of times! Here is the code:
def decorator(argument1, argument2): def shout(wrapped): @wraps(wrapped) def inner(*args, **kargs): print('Before ! '* argument1) ret = wrapped(*args,**kargs) print('After ! '* argument2) return ret return inner return shout @decorator(3, 2)def myfunc(): print('Buy a gift!') myfunc()#++ output:# Before ! Before ! Before !# Buy a gift!# After ! After !Here is the little bit advanced version ,you can see only two layers in the "_deco" function:from functools import partial, wraps def _deco(func, argument): @wraps(func) def inner(*args, **kargs): print('Before ! '* argument[0]) ret = func(*args,**kargs) print('After ! '* argument[1]) return ret return inner #true_decorator = partial(_deco, argument=[3,2])#@true_decorator @partial(_deco, argument=[3,2]) def myfunc(): print('Buy a gift!') myfunc() myfunc.__name__#++ output:# Before ! Before ! Before !# Buy a gift!# After ! After !#++ output:# myfunc
留言
張貼留言