From the beginning to learn python, it has not been very understanding of what the adorner is, and then read a lot of posts and their own hit a lot of code after a little understanding.
I understand the adorner is: in the case of not changing the original function call, packaging it into another function to use, the general purpose is to insert logs, performance testing, transaction processing and so on.
Def host_restrict (tags=[], names=[]): def decorator (f): @functools. Wraps (f) def decorated (*args, **kwargs): Host_info = hosts.get (env.host) if not host_info: return f (*args, **kwargs) if tags and host_info[0] not in tags: raise standarderror (' Tag %s not in %s ' % (host_info[0], tags) If names and not set (names). Intersection ( set ([s for s in Host_info[1].split (' ') if s.strip ()): raise standarderror ( ' Name %s not in %s ' % (host_info[1], names) return f (*args, **kwargs) return Decorated return decorator
The company's decorator is used to constrain the user input information.
The use of adorners is hereby recorded, and the adorner is divided into parametric adorners, parameterless adorners and functions modules.
1 Non-parametric adorner
def foo1 (func): Def decorator (): print ' Some column related operations ' return func () return decorator
2 parametric adorners
2.1 Original function with parameters
def foo1 (func): def decorator (*args,**kwargs): print ' Some column related operations ' return func (*args,**kwargs) return Dec Orator
2.2 Adorner with parameters
# arg for adorner parameter Def FOO3 (ARG): Def decorator (func): Def decoratod (*args,**kwargs): print ' Can judge Arg, calculate the phase Off operation ' return func (*args,**kwargs) return Decoratod return decorator
3 functions Module
This adorner retains the special properties of the decorated function. It can be useful to use reflection in general.
# arg for adorner parameter Def Foo4 (ARG): Def decorator (func): @functools. Wraps (func) def decoratod (*args,**kwargs): print ' Can make some judgments about ARG and other related operations ' return func (*args,**kwargs) return Decoratod return decorator
The following is a reference material, there were many places did not see clearly, the real practice only to understand some:
1. Python Decorator Learning http://blog.csdn.net/thy38/article/details/4471421
2. Python adorner and tangent-oriented programming http://www.cnblogs.com/huxi/archive/2011/03/01/1967600.html
3. Python Decorator's understanding http://apps.hi.baidu.com/share/detail/17572338
4. Python Decorator Learning (nine-step learning) http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html
This article is from "a struggling small operation" blog, please be sure to keep this source http://yucanghai.blog.51cto.com/5260262/1702164
Python's My understanding of adorners