Python small white (no programming foundation, no Computer Foundation) development of the Road Auxiliary Knowledge 2 module

Source: Internet
Author: User

I. Modules and namespaces

In general, Python programs are often made up of multiple module files that are connected by import statements. Each module file is a self-contained variable package, which is a namespace. A module file cannot see the variable name defined by another file, unless it is displayed to import the file, so the module file plays a role in minimizing the naming conflict in the code file. Because each file is a self-contained namespace, even if they spell the same, the variable name of one file does not conflict with a variable in another file.

Note: Import VS from: It should be noted that the FROM statement defeats the purpose of the module's namespace segmentation in a sense, since the from variable is copied from one file to another, which may result in the same name variable being overwritten in the imported file (and, if this happens, Will not give you a warning). This essentially causes namespaces to overlap together, at least on replicated variables.

Second, the module introduction

Modules: Used to logically organize Python code (variables, functions, classes, logic: Implementing a function), which is essentially the. Py end of the python file (file name: test.py, corresponding module name: TEST)

Package: Used to logically organize a module, the essence is a directory (must have a __init__.py file)

Module Categories:
Built-in Modules
Custom Modules
Third-party modules (need to be installed to use)


Note: Modules in Python are called class libraries in other languages.

Iii. Module Import and overloading

Importing and overloading provides a natural choice for program startup, because the import operation will execute the file in the final step.

In a typical application, the importer obtains all the variable names defined at the top level in the module file. These variable names are usually assigned to the tool through module functions, classes, variables, and other exported tools. These will often be used in other files or programs. On the surface, the variable name of a module file can be read by two Python statements--import and from, as well as the reload call.

3.1. Notable features of the module: properties
In a general sense, a module is often a package of variable names, which is considered a namespace. The variable name in a package is called a property: that is, a property is a variable name that is bound to a particular object.

For example, use a text editor to create a single-line Python module file named myfile.py, with the following content:

1234 # cat myfile.py    #!/usr/bin/env python3.5    title = "The Meaning of Life"

When the file is imported, its code runs and generates the properties of the module. This assignment statement creates a property of a module named title.

There are two different ways to get the title property of this module from other components:
First, you can load the module as a whole by using the import statement, and use the module name followed by a property name to get it:

123 >>> importmyfile>>> print(myfile.title)    The Meaning of Life

In general, the DOT expression here represents the syntax of Object.attribute and can take any of its attributes from any object, and this is a common operation in Python code. Here we have used it to get a string variable title in module MyFile, namely Myfile.titile.

Note: Once the module file is imported in the import method, the built-in Dir function can obtain a list of the available variable names within the module.

Second, you can get (actually copy) the variable name from the module file by using the FROM statement: (recommended)

123 >>> from myfile importtitle>>> print(title)    The Meaning of Life

The From and import are similar, but add additional assignments to the variable names of the loaded components. Technically, from copies the properties of the module so that the attribute can become the direct variable of the receiver. Therefore, you can refer to the import string directly as a title (a variable) instead of Myfile.title (a property reference).

Regardless of whether you are using import or from, the module file myfile.py statements are executed, and the imported component (corresponding to this is the interactive prompt mode) Gets the variable name read right in the top-level file. Perhaps there is only one variable name in this simple example (the variable title is assigned to a string), but this concept can be useful if you start defining objects in a module, such as functions and classes. These objects become important components that can be read by one or more client modules through variable names.

In practical applications, module files often define more than one variable name that can be used by external files.

Note: When import and from list module names, they are all using myfile, with no. py suffix. This is because Python searches for the actual file, relying on the path of the Python module to locate the file, and then automatically add the suffix name. However, in the System shell command line, be sure to add the suffix name, but not in the import statement.

3.2, import the module all methods:

123456 importmodule_name #表示将模块中的所有代码加载到这个位置并赋值给变量module_name,并执行模块importlibs.module_name #表示从libs目录下导入模块文件module_name,调用方法:libs.module_name.func()importmodule1_name,module2_name #同时导入多个模块from module_name importlogin,logout#相当于将module_name\login中的代码拿到当前位置执行from module_name importlogin as module_name_login #对导入模块中的方法取别名from libs.module_name importfunc #从目录下的模块文件中导入方法func,调用:func()

Import Essence:
The essence of the import module is to interpret the Python file again.
The essence of the import package is to execute the __init__.py file under the package.

Import Optimizations:
From module_name Import Login
Compared to import module_name, called when Module_name.test (), each call needs to be retrieved in the Os.path path resulting in inefficiency, so use from...import ... Import, which is equivalent to executing the method directly into the caller.

Example

3.3. How Import Works
Import is actually a run-time operation, and the first time a program imports a specified file, it performs three steps:
A. Locate the module file
b, compiled into a bit code (when required)
C. Execute the code of the module to create the object it defines
These three steps will only occur when the module is first imported when the program executes. After that, when the same module is imported, the three steps are skipped, and only the module objects that are loaded in memory are extracted. Python stores the loaded module in a table named Sys.modules (List (Sys.modules.keys ())) and examines the table at the beginning of an import operation. If the module does not exist, a three-step process will be initiated.

A, search

First, Python must find the module file referenced by the import statement. In fact, the path and suffix are deliberately omitted because Python uses the standard module search path to find the module file corresponding to the import statement.

Python's module lookup path:

1234 importsys for item insys.path:  print(item)

  

Search order for Python modules:

12345678 依次从上往下查找(上面的优先,且不再搜索后续路径),如果都没有找到,就报错。D:\oldboy\s14\day5 #执行脚本所在目录D:\oldboy\s14 #忽略这个目录,因为这个目录是因为pycharm自行添加的C:\Users\chen\AppData\Local\Programs\Python\Python35\python35.zipC:\Users\chen\AppData\Local\Programs\Python\Python35\DLLsC:\Users\chen\AppData\Local\Programs\Python\Python35\libC:\Users\chen\AppData\Local\Programs\Python\Python35C:\Users\chen\AppData\Local\Programs\Python\Python35\lib\site-packages

Note: The result returned by Sys.path is a list, and when we need to add a path, just append to the list.

To modify the Python module lookup path:

12 示例:__file__表示当前文件sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))


Module File Selection:

1234567891011 import statement omitted. Python chooses the first file in the search path that matches the import file name. For example, import  b form of import   source code file b.py bytecode file B.pyc directory B, package import compile extension modules (usually written in C or C + +), use dynamic connections when importing (for example, b.so of Linux and B.dll for Windows) compiled built-in modules written in C, and statically connected to Python. The zip file component, which is automatically decompressed when imported. in-memory images for frozen executables. The java class, in the Jython version of Python.

b, compile (optional)
After traversing the module search path and locating the source code file that conforms to the import statement, Python will then compile it into bytecode if necessary.

Python checks the timestamp of the file, and if the bytecode file is found to be older than the source code file (for example, if you have modified the source file), the byte code is automatically regenerated when the program runs. Otherwise, the source code-to-bytecode compilation step is skipped.


C, run
The last step of the import operation is to execute the module's bytecode. All statements in the file are executed sequentially, from beginning to end, and any assignment to the variable name in this step produces the properties of the resulting module file. Therefore, this execution step generates all the tools defined by the module code. For example, a DEF statement in a file is executed at import time to create a function and assign the attributes within the module to those functions. The function can then be called by the importer of the file in the program.


3.4. Heavy Load
By default, it is only run for the first time in each session. After the first import, no other import will work anymore, even changing and saving the module's source code file in another window.

12345678910 cat   script1.py #!/usr/bin/env Python3  print ( Code class= "Bash string" > ' Hello World ' )  $ Python3 >>>  import  script1  # after the first import operation is complete, the file hello World >>>  import  script1  # The second import does not execute >>>

Because of an expensive operation at import time, each file, each program can not be repeated more than once. The import must find the file, compile it into bytecode, and run the code.

However, if you really want Python to run the file again in the same session (without stopping and restarting the session), you need to call the reload function available in the IMP standard library module. The reload function loads and runs the latest version of the file, and if it has been modified and saved in another window, it will reflect the changes.

12345 >>> from imp importreload>>> reload(script1)hello world <module ‘script1‘from ‘/home/chen/script1.py‘>

Python small white (no programming foundation, no Computer Foundation) development of the Road Auxiliary Knowledge 2 module

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.