Python decorators, modules

Source: Internet
Author: User

python decorator

An adorner (decorator) is an advanced Python syntax. Adorners can be used to process a function, method, or class. In Python, we have several methods for working with functions and classes, such as in Python closures, where we see the function object as the result of a function's return. With respect to other methods, the adorner has a simple syntax and a code with high readability. As a result, adorners are widely used in Python projects.

Because the function is also an object, and the function object can be assigned to the variable, so, through the variable can also call the function, suppose we want to enhance the function of functions, for example, before and after the function call to automatically print the log, but do not want to modify the definition of the function, this way in the code when the dynamic increase in function, called (Decorator), Decorator is a higher-order function that returns a function.

Adorner method

    • First, define a simple function that calculates the sum of squares
# get Square Sumdef square_sum (A, B):    return a**2 + b**2
Print (Square_sum (3, 4))

If you want to add a print function to the square_sum () function, the following is the correct wording:
# get Square Sumdef square_sum (A, b):    print ("Intput:", A, b)    return a**2 + b**2

Print (Square_sum (3, 4)

To implement modifications using adorners:
def decorator (F):    def new_f (A, b):        print ("Input", A, b) return        F (A, b)    return New_f
# get Square Sum@decoratordef square_sum (A, B):    return a**2 + b**2
Print (Square_sum (3, 4))
def decorator (F):    def new_f (A, b):        print ("Input", A, b) return        F (A, b)    return New_f
# get Square Sum@decoratordef square_sum (A, B):    return a**2 + b**2
Print (Square_sum (3, 4))

Adorners can be defined in the form of Def, such as decorator in the code above. The adorner receives a callable object as an input parameter and returns a new callable object. The adorner creates a new callable object, which is the new_f above. In New_f, we added the function of printing and realized the function of the original function by calling F (A, B).

After you have defined the adorner, you can use the @ syntax. Call @decorator before the function square_sum definition, actually pass square_sum to decorator, and assign the new callable object that decorator returns to the original function name (square_sum). So, when calling Square_sum (3, 4), it is equivalent to:

Square_sum = Decorator (square_sum) square_sum (3, 4)

In essence, the adorner plays the role of re-pointing to the variable name (name binding), so that the same variable name points to a newly returned callable object, thus achieving the purpose of modifying the callable object, and if there are other similar functions, you can continue to call decorator to modify the function. Instead of repeatedly modifying functions or adding new packages.

Decorator with reference

In an adorner call, such as @decorator, the adorner defaults to the function that follows it as the only parameter. The adorner syntax allows us to invoke decorator, providing other parameters, such as @decorator (a).

# a new wrapper layerdef 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 (' hello ') def square_sum (A, b):    return a**2 + b**2
The pre_str above is an adorner that allows parameters. It is actually a function encapsulation of the original adorner and returns an adorner. We can interpret it as a closure with environmental parameters.
When we call with @pre_str (' hello '), Python can discover this layer of encapsulation and pass parameters to the adorner's environment. The call is equivalent to
Square_sum = pre_str (' Hello ') (square_sum)

Python modules, Packages

1. Import statement

Using the keyword import in Python to introduce a module, for example, to reference the module math, can be introduced in the beginning of the file with import math, the syntax is as follows:

Import Module1[, module2[,... Modulen]

model.py statements

def run ():
Print (' This is the current directory, this is the run function inside the model ')
Def run1 ():
Print (' run1 ')
Def run2 ():
Print (' run2.. ')
Name = 5print (' 66666 ')

model2.py statements
Import model
MODEL.RUN1 ()
Model.run2 ()
Model.run ()

Output:

66666
Test
Run1
Run2.
This is the current directory, which is the run function inside the model

Description: The essence of import is to execute the Python file from beginning to end

2. From...import statement

The FROM statement of Python lets you import a specified section from the module into the current namespace, with the following syntax:

from modname import name1[, name2[, ... Namen]]

From model import RUN,RUN1
Run ()
RUN1 ()

Output:
66666
This is the current directory, which is the run function inside the model
Run1

3. from...import* statement

It is also possible to import all the contents of a module into the current namespace, just use the following declaration:

From modname import *

Note: importing all functions from a module is not recommended for excessive use.

4. Search path and path search

The import of a module requires a process called "Path search".

Search path: Find a group of directories

Path Search: Find an action for a file

Path to the Python search module:
1), the main directory of the program
2), Ptyhonpath directory (if already set)
3), Standard Connection Library directory (generally in/usr/local/lib/python2. x/)
4), the contents of any. pth file (if any). New feature that allows users to add an effective directory to the module search path

importerror:no module named MyModule, this error is said: The module is not in the search path, resulting in a path search failed!
Workaround: 1, add sys.path.append ("module file directory") in the calling file;
2. Using PTH files, create the. pth file in the Site-packages file, write the path of the module in one line
Path, the following is an example, a PTH file can also use annotations:
#. pth file for the My project (this line is a comment), named xxx.pth
C:\Users\Administrator\Desktop\test

5. Package

A package is a form of managing a Python module namespace, with a "point module name", such as a module whose name is A.B, then he represents a sub-module B in package A, such as:

Import sound. Effects. echo

The difference between the package and the folder is that there is a __init__.py under the package, in Python2, if you want to import a Python file under another folder, it must be a package

Python3 don't need it, it's just a folder.








Python decorators, modules

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.