python--Adorner (biased function, assertion)

Source: Internet
Author: User

Blog Address: http://www.cnblogs.com/yudanqu/

  Concept: An adorner is a closure that returns a function as an argument to an alternate version of a function, essentially a function that returns a function

 Adorners are wrapping a shell outside of a function we need, and when we want this function to be more beautiful, you can change the way the package looks, without having to change the original function, or you can avoid an error.

1, simple decorative device
 def   Func2 (func):  def   inner ():  print  ( " ************    ) func ()  return   inner  def   Func1 ():  print  ( " this is one    " ) f  = Func2 (FUNC1) f ()  

Here I explain the adorner, you can see that func1 is the function we really need, when we want to output this function and add some more features, then we need to decorate func1 this function. FUNC2 is an external output function, his parameters are Func, this is just a formal parameter, use the time will need to decorate the function to pass, when we execute FUNC2 this function, there is a function inner (), But the inside inner just created this function without being called (can we understand that when we define a function, he is not automatically called, and we use it to invoke it artificially through this function) the internal read code is read only to the Def inner () and does not go in here, Continue down to return inner, where the internal function name is returned, but only a name has not been called (and the function name is appended with parentheses to be called). Then return to WHO, and give the following F, with F to receive the return value of Func2, now F is the return of the inner. Take the final step, call inner, we already know F is inner, call him to add a parenthesis. After calling the inner function, he has the Func () function inside, and it is called, so the block of statements within Func can be executed directly. Func is the outermost parameter, which is the function we need to decorate. The small partners slowly the idea, must be the first reason clear, then the back is easy.

2, the adorner advanced (contains a parameter)
 def   Func4 (func):  def   inner (age):  if  age < ;  0:age  = 0 func (age)  return   inner  def   func3 (age):  print  ( " this is a-and-%d   "% age) F  = Func4 (FUNC3) F (-7) 

  Look, this frame is almost the same as the first one, except for one more parameter, which is used by the function that we decorated last, and is passed in by the most external. We gave the parameters to the inner function, which is why? Let's think about when the function we decorate is called when the inner function is called, and the inner function is called automatically. So the target function called when the inner function is called, we should not pass the parameters of the objective function from here (the outermost function is a wrapper, he is to return the address of the inner function, to prepare for subsequent calls to inner), we are using F to receive the inner function, We call him also need to add a parenthesis f (), which is called inner, since this call, there is just an interface to pass in parameters, we take advantage of this opportunity to implement the FUNC3 function parameters thrown in, not beautiful, and then we execute the FUNC3 function, Just need to upload the above parameters to their own interface to be good.

22. Improvement
@func4 def func3 (age):     Print ("This is both%d" % age ) # Then you can use the original func3 function directly, do not need to introduce variables to receive, you can already use the content of the adorner func3 (-7)

The @ symbol is the syntactic sugar of the adorner, and when you define a function, you avoid the assignment operation

So what does this piece of code do?

In fact, he can replace the last four lines of the code above, the first adorner in the code is the same, we improved on the use of adorners. We can do this by defining a target function, then passing it as a parameter into the adorner, then using a variable F to receive it, and finally calling F () to do the decorating, is it a bit cumbersome, we do so much work, and we may get dizzy, and we introduce variables, and when the code is long, So many variables how do we remember to live. Then there is the grammatical sugar. You can start using the @ symbol in python2.4. Perhaps you have seen, sometimes there will be @staticmethod, @classmethod words, this is Python's built-in decorator.

The role of @func4 is to replace the above in the adorner to pass the parameters and then assign the value of the process, it can be understood that through such a symbol, it has turned itself into a decorative after the appearance, then we use the time, just as before, call the function, pass the argument can be. Of course it's not true, and when you use this function again below, if you don't add the syntax sugar will be the function itself.

  But at this time the adorner can only receive a parameter, for shaping, because the internal use of judgment, so many of our things are not very convenient, the use of adorners is convenient for us to follow the operation, so we use a different function also has to always modify the adorner. So, let's keep looking down.

3. Advanced Decorative Device (general decorator)
defFunc5 (func):defInner (*args,**Kwargs):#function        Print("&&&&&&") func (*args,**Kwargs)returnInner@func5defFunc6 (name,age,gender=1,number='00000000'):    Print('%s is%d years Old,number is%s,gender:%d'%(Name,age,number,gender)) Func6 ('Zhang San', 18, 0,'05162002')#The parameters of the function are theoretically unlimited, but in practice it is best not to exceed 6 to 7

This is actually not much to say, but to replace the parameters with variable length parameters

*args: can accept unlimited parameters, packaging them into a tuple to the function

**kwargs: You can package keyword parameters into a dictionary to function

With the above two, almost all of the parameters can be entered casually.

4. Finally, incidentally, the partial function and assertion, but this is not the point:
1 " "2 I understand that a partial function is a function that can be achieved by controlling parameters.3 " "4 5 #such a feature, and then implement it6 Print(Int ('1010', base = 2))7 #Base = 2 means that the string is calculated as a binary, which is the binary to determine how much he is, in decimal output8 9 #The first of these methodsTen defInt2 (str, base = 2):#indicates that the setting defaults to 2. Future conversions with base values One     returnInt (str, base) A  - #second method (partial function) - ImportFunctools#This module helps us define the partial function theInt2 = functools.partial (int, base = 2)
1 " "2 Assertion3 " "4 5 deffunc (num, div):6     assert(div! = 0),"Div cannot be 0" #Assertion7     returnnum/Div8 9Func (10, 0)Ten #The denominator of the function itself is nonzero, and if it is zero then an error will be made, using an assertion that does not produce an effect when there is an error, and when there is a mistake, tells you what is wrong.

Yu Tanku (yudanqu)

Blog Address: http://www.cnblogs.com/yudanqu/

python--Adorner (biased function, assertion)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.