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 ! ' *...
留言
張貼留言