Details about python decorator instances and python decorator instances

Source: Internet
Author: User
Tags python decorator

Details about python decorator instances and python decorator instances

I. Scope

In python, there are two types of scopes: global scope and local scope.

The global scope is a variable defined at the file level, function name. The local scope defines the function.

 For scope, we need to understand two points:

A. local variables cannot be accessed globally.

B. You can access the global variables locally, but cannot modify the global variables (of course there are methods to modify them)

Let's take a look at the following example:

X = 1def funx (): x = 10 print (x) # print 10 funx () print (x) # print 1

If the local variable x is not defined, the function searches for x from the inside out. If the variable x is not found, an error is returned.

X = 1def funx (): print (x) funx () print (x) # print out 1x = 1def funx (): def func1 (): print (x) func1 () funx () print (x) # print out 1

Therefore, you only need to remember two points about the scope:

The global variable can be referenced anywhere in the file, but the modification can only be performed globally. If the required variable is not found locally, it will be searched out and an error will be reported if it is not found.

Ii. Advanced functions

We know that the function name actually points to the address of a piece of memory space. Since it is an address, we can use this feature.

Def delete (ps): import OS filename = ps [-1] delelemetns = ps [1] with open (filename, encoding = 'utf-8') as f_read, \ open('tmp.txt ', 'w', encoding = 'utf-8') as f_write: for line in iter (f_read.readline, ''): if line! = '\ N': # process non-empty rows if delelemetns in line: line = line. replace (delelemetns, '') f_write.write (line) OS. remove (filename) OS .rename('tmp.txt ', filename) def add (ps): filename = ps [-1] addelemetns = ps [1] with open (filename, 'A ', encoding = 'utf-8') as fp: fp. write ("\ n", addelemetns) def modify (ps): import OS filename = ps [-1] modify_elemetns = ps [1] with open (filename, encoding = 'utf-8') as f_read, \ open ('tmp. Txt ', 'w', encoding = 'utf-8') as f_write: for line in iter (f_read.readline, ''): if line! = '\ N': # process non-empty rows if modify_elemetns in line: line = line. replace (modify_elemetns, '') f_write.write (line) OS. remove (filename) OS .rename('tmp.txt ', filename) def search (cmd): filename = cmd [-1] pattern = cmd [1] with open (filename, 'R ', encoding = "UTF-8") as f: for line in f: if pattern in line: print (line, end = "") else: print ("not found ") dic_func = {'delete': delete, 'add': add, 'modify ': modify, 'search': search} while True: indium = input ("Enter the operation you want to perform :"). strip () if not indium: continue 1__1 = indium. split () cmd = cmd_1 [0] if cmd in dic_func: dic_func [cmd] (cmd_1) else: print ("Error ")

Use functions as Dictionary values to add, query, modify, and delete text data.

B. The function name can be used as the return value.

Def outer (): def inner (): pass return inners = outer () print (s) ###### output result ####### <function outer. <locals>. inner at 0x000000D22D8AB8C8>

C. The function name can be used as a parameter

Def index (): print ("index func") def outer (index): s = index s () outer (index) ###### output result ######### index func

Therefore, either of the above two conditions can be called an advanced function.

Iii. Closure Functions

The closure function must meet two conditions: 1. The function defined inside the function 2. contains references to the external scope rather than the global scope.

Here are some examples to illustrate the closure function:

Example 1: Only one function is defined in the function, but not the closure function.

Def outer (): def inner (): print ("inner func excuted") inner () # Call and execute the inner () function print ("outer func excuted") outer () # Call and execute the outer function #### the output result is ######### inner func excutedouter func excuted

Example 2: a function is defined in the function and an external variable x is referenced. Is this a closure function? Answer: No

X = 1def outer (): def inner (): print ("x = % s" % x) # reference the variable print ("inner func excuted") inner () in a non-inner function # execute the inner function print ("outer func excuted") outer () ##### output result ######## x = 1 inner func excutedouter func excuted

Let's look back at the definition of the closure function. are both of them satisfied? If you are smart, you must find that the second one is not satisfied. Right, the variable x here is a global variable, not a variable that acts on the domain externally. Let's take a look at the following example:

Def outer (): x = 1 def inner (): print ("x = % s" % x) print ("inner func excuted") inner () print ("outer func excuted") outer () ##### output result ######### x = 1 inner func excutedouter func excuted

Obviously, the above instance meets the conditions of the closure function. Now, you should be clear that, as a closure function, you must satisfy the two conditions mentioned above. However, in general, we will return a value to the closure function. Here we will not explain why. In the following content, you will see the purpose of this return value.

Def outer (): x = 1 def inner (): print ("x = % s" % x) print ("inner func excuted") print ("outer func excuted ") return inner # return internal function name outer ()

Now let's abstract and define the closure function. It is a combination of functions and their related reference environments. When implementing deep constraints, you need to create a thing that can explicitly represent the reference environment and bind it with the relevant subroutine, so as to bundle it into a closure. In the above example, we can find that the closure function must contain its own function and an external variable to be truly called a closure function. If no external variable is bound to it, this function cannot be considered a closure function.

How can we know how many external reference variables A closure function has? Take a look at the following code.

Def outer (): x = 1 y = 2 def inner (): print ("x = % s" % x) print ("y = % s" % y) print (inner. _ closure _) return innerouter () ###### output result ####### (<cell at 0x000000DF9EA965B8: int object at 0x000000006FC2B440>, <cell at 0x000000DF9EA965E8: int object at 0x0000000000006fc2b460>)

The results show that two external local variables are referenced within the inner. If the referenced non-local variable is used, the output here is None.

  Features of closure functions: 1. built-in scope 2. Delayed computing

So what is the function of closure? We know clearly that a closure function is bound to an external environment when it is defined. This is a closure function, so we can use this binding feature to complete some special functions.

Example 3: Download the page source code based on the input URL

From urllib. request import urlopendef index (url) def get () return urlopen (url ). read () return getpython = index ("http://www.python.org") # return the get function address print (python ()) # execute the get function and print the returned results out baidu = index ("http://www.baidu.com") print (baidu ())

Some people may say that this does not meet the condition of the closure function! I have not referenced non-global external variables. In fact, this is not the case. As we have said before, all variables in the function belong to the function. Then, in index (url), the url also belongs to the function, but we omit the step. Therefore, the above function is also a closure function.

4. decorator

With the above foundation, you can understand the decorator.

Decorator: name of the decorated function passed in by the external function. The internal function returns the name of the decorated function.

Features: 1. do not modify the call method of the decorated function. 2. do not modify the source code of the decorated function.

A. No parameter decorations

For the following example, we need to calculate the code execution time.

import time, randomdef index():  time.sleep(random.randrange(1, 5))  print("welcome to index page")

According to the characteristics of the decorator, we cannot modify index (), and the call method cannot be changed. At this time, we can use the decorator to complete the above functions.

Import time, randomdef outer (func): # pass the index address to func def inner (): start_time = time. time () func () # fun = index is the address where func saves the external index function end_time = time. time () print ("Run time % s" % (end_time-start_time) return inner # return inner address def index (): time. sleep (random. randrange (1, 5) print ("welcome to index page") index = outer (index) # Here the inner address is returned and assigned to indexindex () again ()

However, in some cases, parameters need to be passed into the decorated function, and some functions do not need parameters. How can this variable parameter function be handled? Let's take a look at the use of the parameter decorations.

B. Parameter decorations

Def outer (func): # pass the index address to func def inner (* args, ** kwargs): start_time = time. time () func (* args, ** kwargs) # fun = index is the address where func saves the external index function end_time = time. time () print ("Run time % s" % (end_time-start_time) return inner # return inner address

Here are some examples of other situations.

If the decorated function has a return value

Def timmer (func): def wrapper (* args, ** kwargs): start_time = time. time () res = func (* args, ** kwargs) # res receives the return value of the home function: stop_time = time. time () print ('run time is % s' % (stop_time-start_time) return res return wrapperdef home (name): time. sleep (random. randrange (123123123123123123123123123123123123123123) print ('welecome to % s HOME page' % name) return

Here, we add the following call method to execute the decorated function:

Home = timmer (home) # The wrapper memory address is returned on the right side of the equation, and then assigned to home. The home here is not the original function, instead, the function is decorated.

Python provides us with a convenient method, such as home = timmer (home @.

In the future, we will write @ timmer before the function to be decorated. The effect is the same as that of home = timmer (home.

If a function is decorated by multiple decorators, what is the execution order.

import timeimport randomdef timmer(func):  def wrapper():    start_time = time.time()    func()    stop_time=time.time()    print('run time is %s' %(stop_time-start_time))  return wrapperdef auth(func):  def deco():    name=input('name: ')    password=input('password: ')    if name == 'egon' and password == '123':      print('login successful')      func() #wrapper()    else:      print('login err')  return deco@auth  # index = auth(timmer(index))         @timmer # index = timmer(index)def index():  time.sleep(3)  print('welecome to index page')index()

The experimental results show that the execution sequence of a function is from bottom to top when multiple decorators are decorated with one function.

Summary

The above is a detailed explanation of the python decorator instance introduced by xiaobian. I hope it will help you. If you have any questions, please leave a message and I will reply to you in time. Thank you very much for your support for the help House website!

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.