Python deep learning decorator and python deep learning and Decoration

Source: Internet
Author: User
Tags python decorator

Python deep learning decorator and python deep learning and Decoration

Decorator is an advanced Python syntax. The decorator Can process a function, method, or class. In Python, we have multiple methods to process functions and classes. For example, in the Python closure, we can see the function object as the return result of a function. Compared with other methods, the decorator has simple syntax and high code readability. Therefore, the decorator is widely used in Python projects.

The decorator first appeared in Python 2.5. It was initially used for callable objects such as processing functions and methods (such as the _ call _ method ). In Python 2.6 and later versions, the decorator is further used for processing classes.

Decoration functions and methods

We first define two simple mathematical functions, one for calculating the sum of squares and the other for calculating the square difference:

Copy codeThe Code is as follows:
# Get square sum
Def square_sum (a, B ):
Return a ** 2 + B ** 2

# Get square diff
Def square_diff (a, B ):
Return a ** 2-B ** 2

Print (square_sum (3, 4 ))
Print (square_diff (3, 4 ))

After having basic mathematical functions, we may want to add other functions for functions, such as printing input. We can rewrite the function to achieve this:

Copy codeThe Code is as follows:
# Modify: print input

# Get square sum
Def square_sum (a, B ):
Print ("intput:", a, B)
Return a ** 2 + B ** 2

# Get square diff
Def square_diff (a, B ):
Print ("input", a, B)
Return a ** 2-B ** 2

Print (square_sum (3, 4 ))
Print (square_diff (3, 4 ))

We modified the function definition and added the function.

Now, we use the decorator to implement the above modification:

Copy codeThe Code is as follows:
Def decorator (F ):
Def new_F (a, B ):
Print ("input", a, B)
Return F (a, B)
Return new_F

# Get square sum
@ Decorator
Def square_sum (a, B ):
Return a ** 2 + B ** 2

# Get square diff
@ Decorator
Def square_diff (a, B ):
Return a ** 2-B ** 2

Print (square_sum (3, 4 ))
Print (square_diff (3, 4 ))

Decorator can be defined in the format of def, such as decorator in the code above. The decorator receives a callable object as the input parameter and returns a new callable object. The modifier creates a new callable object, namely the new_F above. In new_F, the printing function is added and the original function is implemented by calling F (a, B.

After the decorator is defined, we can use the @ syntax. Call @ decorator before the square_sum and square_diff functions are defined. We actually pass square_sum or square_diff to decorator, and assign the new callable object returned by decorator to the original function name (square_sum or square_diff ). Therefore, when we call square_sum (3, 4), it is equivalent:
Copy codeThe Code is as follows:
Square_sum = decorator (square_sum)
Square_sum (3, 4)

We know that the variable names and objects in Python are separated. The variable name can point to any object. In essence, the modifier acts as a name binding to redirect the same variable name to a new callable object, this allows you to modify callable objects.

Similar to the processing function, we can use the decoration machine processing method.

If we have other similar functions, we can continue to call the decorator to modify the function, instead of repeatedly modifying the function or adding new encapsulation. In this way, we have improved the reusability of the program and increased the readability of the program.

Parameter-included decorators

In the above decorator call, for example @ decorator, the function next to the decorator is a unique parameter by default. The decorator syntax allows us to provide other parameters when calling decorator, such as @ decorator (). In this way, it provides more flexibility for writing and using the decorator.

Copy codeThe Code is as follows:
# A new wrapper layer
Def pre_str (pre = ''):
# Old decorator
Def decorator (F ):
Def new_F (a, B ):
Print (pre + "input", a, B)
Return F (a, B)
Return new_F
Return decorator

# Get square sum
@ Pre_str ('prop _^ ')
Def square_sum (a, B ):
Return a ** 2 + B ** 2

# Get square diff
@ Pre_str ('t_t ')
Def square_diff (a, B ):
Return a ** 2-B ** 2

Print (square_sum (3, 4 ))
Print (square_diff (3, 4 ))

The pre_str above is a modifier that allows parameters. It is actually a function encapsulation of the original decorator and returns a decorator. We can understand it as a closure containing environment parameters. When we call it using @ pre_str ('prop _^ '), Python can discover the encapsulation of this layer and pass the parameters to the decorator environment. This call is equivalent:
Copy codeThe Code is as follows:
Square_sum = pre_str ('prop _^ ') (square_sum)

Decoration

In the preceding example, the modifier receives a function and returns a function to process the function. After Python 2.6, the decorator is extended to the class. A decorator can receive a class and return a class to achieve the processing effect.

Copy codeThe Code is as follows:
Def decorator (aClass ):
Class newClass:
Def _ init _ (self, age ):
Self. total_display = 0
Self. wrapped = aClass (age)
Def display (self ):
Self. total_display + = 1
Print ("total display", self. total_display)
Self. wrapped. display ()
Return newClass

@ Decorator
Class Bird:
Def _ init _ (self, age ):
Self. age = age
Def display (self ):
Print ("My age is", self. age)

EagleLord = Bird (5)
For I in range (3 ):
EagleLord. display ()

In decorator, we return a new class newClass. In the new class, we record the object (self. wrapped) generated by the original class and append the new attribute total_display to record the number of times display is called. We also changed the display method.

Through modification, our Bird class can display the number of times display is called.

Summary

Name binding is the core function of the decorator. This syntax is another embodiment of the Python multi-programming paradigm. Most Python users do not need to define decorator, but may use decorator. In view of the wide use of decorator in Python projects, it is very helpful to understand this syntax.


How should I understand the python decorator?

The so-called decorator is to wrap the function and add some additional functions for the function. The decorator is a function. The parameter is the encapsulated function and the encapsulated function is returned: You can try again:
Def d (fp): def _ d (* arg, ** karg): print "do something before fp .. "r = fp (* arg, ** karg) print" do something after fp .. "return r return _ d @ ddef f (): print" call f "# The above @ d is used to indicate the decorator and the following: # f = d (f) f () # Call f

How can I use a decorator in python?

I don't know. Maybe I can't jump out of the main function in the 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.