Python note decorator (decorator)

Source: Internet
Author: User

All objects in Python, variables are objects, functions are objects

Def funcName ():

Return 1

F = funcName #funcName is a function name and the name of an object, so you can assign a value to a variable, assign the object funcName to the variable F

F () # through the variable F to implement the function FuncName function call execution, F () =funcname ()

An adorner is essentially a function that extends existing functions without modifying the original code. Its principle is that the original function object is passed as a parameter to the adorner function, and returns the result of the original function execution. This process is the decoration process of the decorator. And we'll

First we look at a simple example: if we have 2 departments, one is the development department, the technical module of this function is provided by the development Department (that is, home, TV, movie these functional modules are built by the development department),

Another one is the operations department. They are assigned to invoke the functionality of these underlying platforms (the Home,tv,moive function), which is called by Home,tv,moive, which is their execution. )

Three functional modules built by developers:

Def home ():

res = print ("Welcome to my home page")

return res

Def TV ():

res = print ("Welcome to my TV page")

return res

def movie ():

res = print ("Welcome to my Movie page")

return res

Operations Department colleagues call three function modules:

Home () # Call and execute the home function

TV () # Call and execute the TV function

Moive () invokes and executes the Movi function

Running the code and returning the result is:

"Welcome to my home page"

"Welcome to my TV page"

"Welcome to my Movie page"

This is a functional module that has been defined, three functions, a home, a TV, a moive, a requirement, to add a verification login function to these three functions. What to do?

Let's take a look at what better way to achieve this demand function. Before executing the home,tv,moive function, I need to verify it first. What if this verification function function is written?

def login (func):

Print ("Verify, you can accss my web site")

return func

Def home ():

res = print ("Welcome to my home page")

return res

Def TV ():

res = print ("Welcome to my TV page")

return res

def movie ():

res = print ("Welcome to my Movie page")

return res

Operations personnel need to use the above function module, will execute the following code call:

Home = Login (home) # Pass the home function as a parameter to login and login execution calls login (), note that returning this parameter is the function

Home ()

TV = login (TV)

TV ()

moive = Login (moive)

Moive ()

Executing this code, the returned result is:

"Verify, you can accss my web site"

"Welcome to my home page"

"Verify, you can accss my web site"

"Welcome to my TV page"

"Verify, you can accss my web site"

"Welcome to my Movie page"

Note: Home = login (home) as long as the function is enclosed in parentheses, it is executed. So the login function executes, and the home function does not have parentheses just as to pass the parameter to login, assigning the execution result of login to the parameter function.

Although the above code can meet the needs of the user, there is not much to modify the existing code place, but you think, if you are the Operations department, the developer provided the home, TV, moive function module, also added the login module, and you need to call your function module, Before calling Home,tv,moive, they need to add: Home = Login (home), TV = login (TV), moive = Login (moive), although the changes are not very large, but still let you modify the existing code, You're not going to complain a lot about developers, though, just add a code before each call.

So what better way to solve this problem, not to modify the existing code on the basis of. Just expanded the new function module, and that's what we're going to cover next--adorners.

Next we'll look at the adorner, if you want to define a login decorator, and use this adorner in the existing functionality. Because the adorner itself is a function, I'll define the adorner function next.

1 extension of the function module for functions without parameters:

def login (func): # func is the original function object (containing the Home Function object/tv function object/movie function object) passed as a parameter to the Decorator function login, then returns the result of the original function execution

def inner ():

Print ("Verify,you can access it")

return func ()

return inner

@login

Def home ():

res = print ("Welcome to my home page")

return res

@login

Def TV ():

res = print ("Welcome to my TV page")

return res

@login

def movie ():

res = print ("Welcome to my Movie page")

return res

Operations personnel need to use the above function module, will execute the following code call:

Home ()

TV ()

Moive ()

2 Adorner original function with indeterminate parameter (dynamic parameter) function uncertain adorner with several parameters

def login (func): # Passing a Function object as a parameter to the adorner function login

def inner (*args,**kwargs): # Decorating inline functions

Print ("Verify You can access it") #新功能函数被包含在装饰器内嵌函数里

return func (*args,**kwargs) #返回原函数对象执行结果 with parameter

return inner #返回装饰内嵌函数对象

@login

Def home ():

res = print ("Welcome to my home page")

return res

@login

def TV (Name,password):

res = print ("Welcome%s to my TV page"%name)

return res

@login

def movie (Name,id):

res = print ("Welcome%s and%d to my movie page"% (Name,id))

return res

Basically mastering the usage of the above 2 kinds of adorners, can solve most of the problems.

The first two are the use of functions with parameters or adorners with dynamic parameters, and then we end up with the use of the adorner's own parameters, but what kind of scene does it use? For example, login to verify the function function, it has many kinds of authentication methods, there are account password authentication, LDAP authentication, ad authentication, key authentication and so on, operation and maintenance departments need to verify, go to invoke what login, this we can use with parameters of the adorner to complete.

def loginmaker (*args,**kwargs): # Overlay the decorator Login

def login (func):

def inner (*args,**kwargs):

Print ("Verfiy can use it")

return func ()

return inner

Return to login #返回这个装饰器对象

@loginmaker ("Calda\bjdong", "123445") # Authentication of the ad

Def home ():

res = print ("Welcom to My home page")

return res

@loginmaker ("Daofnda8823ndfafdafds_$ferae") # Key Certification

def TV (Name,password):

res = print ("Welcome%s to my TV page")

@loginmaker ("Joice", "1234455") # Account Authentication

def moive (Nickname,id):

res = print ("Welcome%s your ID is%d"% (Nickname,id))

Home ()

TV ()

Movie ()

Python note decorator (decorator)

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.