python decorator simple example
Why we need the decorator in python ?
Let's see a example:
#!/usr/bin/python def fun_1(x): return x*2 def fun_2(x): return x*x*2 if __name__ == '__main__': print 'call fun_1' print fun_1(8) print 'call fun_2' print fun_2(9)
We can see more than code heavy:
so we don't want to write the below code any more ...
print 'call fun_1' print 'call fun_2'
How can we do it with a simple way !
Try use decorator:
#!/usr/bin/python def fun_decorator(f): def fn(x): print 'call '+f.__name__ return f(x) return fn @fun_decorator def fun_1(x): return x*2 @fun_decorator def fun_2(x): return x*x*2 if __name__ == '__main__': print fun_1(8) print fun_2(9)
See the result below:
But,sometime We are expect to write something before or after tips:
something like below,we add some at the head ..
How to make it ?
a simple and stupid method below:
#!/usr/bin/python def fun_decorator(f): def fn(x): print 'call '+f.__name__ return f(x) return fn @fun_decorator def fun_1(x): return x*2 @fun_decorator def fun_2(x): return x*x*2 if __name__ == '__main__': print 'INFO',fun_1(8) print 'DEBUG',fun_2(9)
You can see,we are just simply add some string before call function !
So,How to make it easy ..
#!/usr/bin/python def fun_decorator(user_info): def wrapper(f): def fn(x): print '%s call %s' % (user_info,f.__name__) return f(x) return fn return wrapper @fun_decorator('INFO') def fun_1(x): return x*2 @fun_decorator('DEBUG') def fun_2(x): return x*x*2 if __name__ == '__main__': print fun_1(8) print fun_2(9)
If you function with more than one argument,How can we do ?
#!/usr/bin/python def fun_decorator(user_info): def wrapper(f): def fn(x,y): print '%s call %s' % (user_info,f.__name__) return f(x,y) return fn return wrapper @fun_decorator("INFO") def fun_1(x,y): return x*y @fun_decorator("INFO") def fun_2(x,y): return x*y*2 if __name__ == '__main__': print fun_1(2,3) print fun_2(2,3)
Okay,Sometime,we even don't know how many arguments will be input ?
so,How can we do ?
>>>we will answer it next time ! Thank you
Can we drop this masquerade