New Year Good ~ So, a long time has not been updated, actually think also has not much to write, because the Python document seems very comprehensive said ... Can do almost only translation and collation, the English clearance of friends may wish to go directly to doc.python.org here to view relevant information:)
Reprint please indicate the original author and original address, thank you!
Let's talk about decorators today. The adorner is a well-known design pattern, which is often used in scenes where there is a demand for facets, with the classic insert log, performance test, transaction processing, and so on. Decorators are a great design for solving such problems, and with adorners, we can pull out a lot of the same code that is not relevant to the function itself and continue to reuse it. In summary, the function of an adorner is to add additional functionality to an already existing object.
1. Adorner Primer 1.1. How is the demand coming?
The definition of adorners is very abstract, let's look at a small example.
def foo (): print ' in foo () ' foo ()
This is a very boring function, yes. But suddenly there is a more boring person, we call him B-June, said I want to see how long it takes to execute this function, OK, then we can do this:
Import timedef foo (): start = Time.clock () print ' in foo () ' end = Time.clock () print ' used: ', end-startf OO ()
Very well, the features look impeccable. But the egg-ache B-June suddenly don't want to see this function, he to another called Foo2 's function produced a more intense interest.
What do we do? If the above new additions to the code to copy into the Foo2, which made a big taboo ~ Copy what is not the most annoying it! And what if B-June continues to look at the other functions?
1.2. Status quo, is change also
Remember, the function is a one-time citizen in Python, so we can consider redefining a function Timeit, passing the Foo reference to him, then calling Foo in Timeit and timing it so that we do not have to change the Foo definition, and, No matter how many functions B has seen, we don't have to modify the function definition!
Import timedef foo (): print ' in foo () ' Def Timeit (func): start = Time.clock () func () end =time.clock () C4/>print ' used: ', End-starttimeit (foo)
There seems to be no logical problem, everything is fine and functioning properly! ...... Wait, we seem to have modified the code for the calling section. Originally we called this: Foo (), modified to become: Timeit (foo). In this case, if Foo is called at N, you will have to modify the code in the N place. Or, to be more extreme, consider that the code in which it is called cannot modify the situation, for example: This function is something you give to someone else.
1.3. Minimize Changes!
That being the case, we'll try to figure out how to do this without modifying the calling code, which means that calling Foo () requires the effect of calling Timeit (foo). We can think of assigning Timeit to Foo, but Timeit seems to have a parameter ... Think of ways to unify the parameters! If Timeit (foo) does not directly produce a call effect, but instead returns a function that is consistent with the Foo argument list ... It's good to have the return value of Timeit (foo) assigned to Foo, and then the code that calls Foo () doesn't have to be modified at all!
#-*-coding:utf-8-*-import timedef foo (): print ' in foo () ' # defines a timer, passes in one, and returns another method with the chronograph function added Def Timeit (func): # Define an inline wrapper function that adds the timer function to the incoming function. def wrapper (): start = Time.clock () func () end =time.clock () Print ' Used: ', End-start # Returns the Wrapped function to return Wrapperfoo = Timeit (foo) foo ()
In this way, a simple timer is ready! We only need to call Foo after the definition of foo, and foo = Timeit (foo), to achieve the purpose of timing, which is the concept of adorners, which looks like Foo was Timeit decorated. In this example, the function enters and exits with timing, which is called a cross plane (Aspect), which is called aspect-oriented programming (Aspect-oriented programming). In comparison to the top-down execution of traditional programming habits, a logic is inserted horizontally in the process of function execution. In a specific business area, you can reduce the amount of repetitive code. Aspect-oriented programming there are quite a lot of terminology, here is not much to do introduction, interested in the words can find relevant information.
This example is for demonstration purposes only, and does not consider Foo with parameters and a return value of the case, the task of perfecting it to you:)
2. Additional support for Python 2.1. Grammar sugar
The above code seems to be no longer streamlined, and Python provides a syntactic sugar to reduce the amount of character input.
Import Timedef Timeit (func): def wrapper (): start = Time.clock () func () end =time.clock () print ' Used: ', End-start return wrapper@timeitdef foo (): print ' in foo () ' foo ()
Focus on the 11th line of @timeit, add this line to the definition and the other write foo = Timeit (foo) is completely equivalent, do not think that @ has another magic. In addition to the less character input, there is an additional benefit: it looks more like a decorator.
2.2. Built-in adorner
There are three built-in decorators, Staticmethod, Classmethod, and property, respectively, to make the instance methods defined in the class into static, class, and class properties. Because functions can be defined in a module, static and class methods are not much useful unless you want to fully object-oriented programming. Attributes are not essential, and Java does not have the properties to live very well. From my personal Python experience, I have not used the property, and the frequency of using Staticmethod and Classmethod is very low.
Class Rabbit (object): def __init__ (self, name): self._name = name @staticmethod def newrabbit (name) : return Rabbit (name) @classmethod def newRabbit2 (CLS): return Rabbit (") @property def name (self): return Self._name
The attribute defined here is a read-only property, and if it is writable, a setter needs to be defined:
@name. Setter def name (self, name): self._name = name
2.3. Functools Module
The Functools module provides two adorners. This module was added after Python 2.5, and generally everyone should use more than this version. But my usual working environment is 2.4 t-t
2.3.1. Wraps (wrapped[, assigned][, updated]):
This is a very useful decorator. A friend who has seen the previous reflection should know that the function has several special properties such as the function name, after being decorated, the function name Foo in the above example becomes the name of the wrapper function wrapper, and if you want to use reflection, it can result in unexpected results. This decorator solves this problem by preserving the special properties of the decorated function.
Import Timeimport functoolsdef Timeit (func): @functools. Wraps (func) def wrapper (): start = Time.clock () func () end =time.clock () print ' used: ', End-start return wrapper@timeitdef foo (): print ' in foo () ' foo () print foo.__name__
Notice the 5th line first, and if you comment on this line, foo.__name__ will be ' wrapper '. In addition, I believe you have noticed that this decorator has a parameter. In fact, he has two other optional arguments, the property names in assigned are replaced with assignments, and the property names in updated are merged using update, and you can get their default values by looking at the source code of Functools. For this adorner, it is equivalent to wrapper = Functools.wraps (func) (wrapper).
2.3.2. Total_ordering (CLS):
This adorner is useful for certain occasions, but it is added after Python 2.7. Its role is to implement at least __lt__, __le__, __gt__, __ge__ one of the classes plus other comparison methods, this is a class adorner. If you feel bad, take a closer look at the source code of this adorner:
53def total_ordering (CLS): "" "Class decorator that fills in missing ordering methods" "" "Convert = {56 ' __ Lt__ ': [(' __gt__ ', lambda Self, other:other < self), (' __le__ ', lambda-Self, other:not other < Self), (' __ge__ ', lambda-Self, other:not-< Other)],59 ' __le__ ': [(' __ge__ ', Lambda se LF, Other:other <= self), (' __lt__ ', lambda-Self, other:not-other <=-self), 61 (' __gt__ ', lambda Self, other:not-<= other)],62 ' __gt__ ': [(' __lt__ ', lambda-Self, other:other > Sel f), (' __ge__ ', lambda Self, other:not other > Self), + (' __le__ ', Lambda self, O Ther:not self > Other)],65 ' __ge__ ': [(' __le__ ', lambda-Self, other:other->=-Self), 66 (' _ _gt__ ', lambda Self, other:not->= self), (' __lt__ ', lambda-Self, other:not->= Other )]68}69 roots = sET (CLS) & Set (convert) roots:71 raise ValueError (' must define at least one ordering operation: < > <= >= ') root = max (roots) # prefer __lt__ to __le__ to __gt__ to __ge__73 for Opname, Opfun C in convert[root]:74 if Opname not in roots:75 opfunc.__name__ = opname76 opfunc.__doc__ = g etattr (int, opname). __doc__77 setattr (CLS, Opname, Opfunc) return CLS
This article is all over here, if you have time, I will tidy up an adorner for checking the parameter type of the source code put up, is an application it:)
Python adorner and aspect-oriented programming