Python3 ornament and python3 Ornament

Source: Internet
Author: User

Python3 ornament and python3 Ornament
Python3 decorator 1. Closure

The closure has two conditions: the function contains an inner function, and the inner function references the variable defined by the outer function.

Eg:

Def outer ():

X = 10

Def inner ():

Print (x)

Return inner

2. decorator

The modifier is used to add functions without changing the source code of the original function. Execution Process: when calling a function modified by the decorator, the decorator is called first, passing the function name of the decorator function into the decorator function, and executing the inner function of the decorator, the inner function calls the decorated function to execute the decorated function. The added function is written in the inner function, so the added function is also implemented. The advantage of doing so is that the call method of the function to be decorated remains the same, so as to prevent the phenomenon of moving the whole body; the source code of the function to be decorated is not changed, in line with the open and closed principle.

Note that the decorator function must be a closure function.

Eg:

Decorator functions:

ImportTime
DefShow_time (f ):
DefInner (* args, ** kwargs): # sets the variable length parameter to prevent the decoration function from having parameters.
Start_time = time. time ()
F (* args, ** kwargs)
Time. sleep (3)
End_time = time. time ()
Print ('End _ time = % s'% (End_time-start_time ))
ReturnInner ()

 

@ Show_time
DefFoo (): # function modified by the decorator
Print ('OK')

Foo () # Call a function

If you want to transmit parameters to the decorator function, an external function is added to the periphery of the decorator function.

Eg2:

Def outer (* args ):

Def show_time (f ):

Def inner (* args, ** kwargs ):

Pass

Return inner

Return show_time

 

@ Outer ('parameter ')

Def foo ():

Pass

 

Foo () # Call a function

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.