Python Learning Notes-adorners

Source: Internet
Author: User

This section understands the simple use of some adorners.


First of all, a preliminary knowledge, a function as a parameter, passed into another function

For example, I passed outer (F1), I passed in F1 's memory address, A=func () actually executed the F1 () function and assigned the return value to a, so when I printed print (a), he would output Hee

>>> def outer (func): Print (func) A=func () print (a) def F1 (): Print ("AAA") return "Hee" outer (F1)---- --------<function F1 at 0x0000023d3ff3d510>aaahee

The adorner (decorator) is a function that can be used as a pass-through, he can be unified to some functions to add some "modifier" function, but do not destroy the original code. The adorner itself is also a function, when other functions call him, in front of other functions @ + adorner name format is OK


This format performs 2 functions:

1. Automatically executes the adorner function and passes the function name F1 below as a parameter

2. Re-assign the return value of the adorner function to F1

In a nutshell, that's it.

F1=decortor (F1)


Change the above example slightly to an adorner, as shown below, and the result is the same

def outer (func): Def innner (*args,**kwargs): Print (func) a=func (*args,**kwargs) print (a) RE Turn a return innner@outerdef F1 (): Print ("AAA") return "Hee" F1 ()



Let's look at another complex example:

I have defined 3 function f1,f2,f3, they have different parameters, I need each function to add a ' before ' in front of the result now, and then add a ' after ' to the result


def outer (func): Def inner (*args, **kwargs): Print (' before ') R = func (*args, **kwargs) print (' Afte     R ') return R return inner@outerdef F1 (ARG): Print (ARG) return "F1" @outerdef F2 (a1, A2): Print ("F2") @outerdef f3 (): Print ("F3") F1 ("HHH") F2 ("BBB", 444) F3 ()


The results are as follows:

Beforehhhafterbeforef2afterbeforef3after


Note The main points:

    1. When using the adorner outer, he passes the parameter outer (F1), where the F1 address is passed, R=func () actually executes F1 () and assigns the return value to r, where the purpose is to ensure that the result returned by the inner is the same as the result of the F1 return Finally, the decorated inner function address is assigned to F1 to achieve the decoration effect;

    2. Remember the previous universal parameter F (*args,**kwargs), can accept arbitrary parameters


Example 2: adorners A widely used scenario is login verification, and many features must be judged before they can be used.

The following example decorator uses a global variable login_user to determine if it is already logged in.

#!/usr/bin/env python# -*- coding:utf-8 -*-login_user = {"Is_login":  False  }def outer (func):     def inner (*args, **kwargs):         if login_user[' Is_login ']:             r = func ()              return r        else:             print ("Please login")     return innerdef outer1 (func) :     def inner (*args, **kwargs):         if login_user[' is_login '] and login_user[' User_type '] == 2:             r = func ()              return r        else:             print ("Please login, or not enough permission")     return  Inner@outer1def order ():     print ("Welcome to%s Login"  % login_user[' current_user ') @ Outerdef changepwd ():     print ("Welcome to%s Login"  % login_user[' current_user ') @ Outerdef manager ():     print ("Welcome to%s Login"  % login_user[' Current_User ') def  login (user, pwd):    if user ==  "Alex"  and pwd ==   "123":         login_user[' Is_login '] = true         login_user[' Current_User '] = user         manager () Def main ():    while true:         inp = iNput ("1, background management; 2, login")         if inp ==  ' 1 ':             manager ()          elif inp ==  ' 2 ':             username = input ("Please enter user name")              pwd = input ("Please enter password")              Login (USERNAME,&NBSP;PWD) Main ()


Example 3.

If there is more than one adorner, I can use it nested, because the first layer of the adorner is actually a function, then he can continue to be decorated.


For example, notice that his call order is from bottom to top.

python 3.5.2  (v3.5.2:4def2a2901a5, jun 25 2016, 22:18:55)  [MSC v.1900  64 bit  (AMD64)] on win32>>> def outer (func):     def innner (*args,**kwargs):         print (func)          a=func (*args,**kwargs)          Print ("Trim 1")         return a    return  Innnerdef outer2 (func):     def inner (*args,**kwargs):         print (func)         a=func (*args,**kwargs)         print ("Decoration 2")          RETURN&NBSP;A&NBSP;&NBSP;&NBSP;&NBSP;RETURN&NBSP;INNER@OUTER2@OUTERDEF&NBSP;F1 ():     print ("original function")     return  "Hee" F1 () <function outer.<locals>.innner at 0x000001FF89A6D620>< function f1 at 0x000001ff89a6d598> original function decoration 1 decoration 2


650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M00/86/A5/wKioL1fGfAvwfoMgAAB_lmOBgy0357.png "title=" Capture.png "alt=" Wkiol1fgfavwfomgaab_lmobgy0357.png "/>

This article is from the "Mapo Tofu" blog, please be sure to keep this source http://beanxyz.blog.51cto.com/5570417/1844747

Python Learning Notes-adorners

Related Article

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.