Python--5, module

Source: Internet
Author: User

Module

The Code of the program writes multiple files according to the function, and these files are referenced to each other to implement the functions of the program, which are called "modules".
A function or variable that you define in order to prevent it from being lost after execution in the interpreter, you need to write the code to the file, and then execute it directly, called "script".
However, after more and more functions, in order to manage the code, a program is usually divided into several files, which makes the program structure clearer and easier to manage. That's it. They are used as modules to import into other modules. The function multiplexing is realized.
In the same vein, we can also use the modules that others have written to import into their own projects to improve the efficiency of development.

A module is a file that contains Python definitions and declarations, and modules are typically used for import.

The modules that import can load are:

    • . py files written by Python
    • C or C + + extensions that have been mutated into shared libraries or DLLs
    • Bar a series of modules organized into folders together (the concept of package is introduced later)
    • Use the built-in modules written in C and linked to the Python interpreter.

Example:

#test.pyprint(‘this is test‘)number = 123def ins1(): print(‘test模块‘,number)def ins2(): print(‘test模块‘) ins1()def ins3(): global number number = 0
Import

A module can contain executable statements and definitions of functions in order to initialize the module. They are executed when the module is imported for the first time (even if the same module is importing many times in a program, only the module is loaded into memory the first time it is imported, and subsequent imports are only referenced)

Note: We can find the module that is currently loaded from Sys.module, Sys.module is a dictionary that contains the mapping of the module name to the module object, which determines whether the import module needs to be re-imported.

Import Importing Process

Creates a new namespace for the corresponding module, executes the code contained in the module in the newly created namespace, and creates a module name to reference the namespace.

    • The imported module has a separate namespace for the entire import module

Each module being imported is a separate namespace, and the function defined in the module treats the module as a global namespace, preventing the global variables of the module from conflicting with the global variables of the file that called it.

    • Alias the module
import test as ttprint(tt.money)

For example two similar modules have two functions of the same method. According to the user input to determine which module, and then to the module as a specific alias. \

    • Importing multiple modules on a single line
import module1,module2,……
From module_name import func vs. import
    • From.. Import: The method name in the module is imported directly into the current namespace so, in the current file namespace, use the name directly.
      If the imported module method also needs to return the original module method or variable, then the original module will prevail.
      If the imported module method conflicts directly with the method in the present file, the import will be overwritten.
    • also supports as, which aliases the imported methods.
    • also supports "," Importing multiple
From.. Import *

Imports the name of the module that starts with an underscore other than "_" in the current position.
This can be used __all__ to control the method of * import.
#__all__ =[' money ', ' read1 '] #这样在另外一个文件中用from spam import * This can import two names specified in the list

Overloading of modules (not important)

After the module is imported, it is placed in the Sys.module dictionary. If you change the contents of the module, you must restart the program. Python does not support reloading or uninstalling previously imported modules.
Even if the module object is deleted in the Sys.module, it is still possible to be referenced by other program components. Will not be cleared away.
In particular, it refers to a class in this module that produces a lot of objects with this class, so these objects have references to this module.

Two kinds of Python files
    • Script: A file is the entire program that is used for execution.
    • Module: The file contains a bunch of features that are used for import.

Python built-in global variable __name__

    • When a file is executed as a script: __name__ equals ' __main__ '
    • When a file is imported as a module: __name__ equals module name

Used to control the. py file to perform different logic under different application scenarios.

The search path for the module

The modules that are contained in the Sys.path path, built-in modules, in-memory modules that have already been loaded.
#我们自定义的模块名不应该与系统内置模块重名.

You can add environment variables by modifying Sys.path.

import syssys.path.append(‘/a/b/c‘)sys.path.insert(0,‘/x/y/z‘)

Search environment variables will be found in Sys.path from left to right, Sys.path can also contain. zip files and. egg files, Python will treat. zip files as a directory.

#.egg files are packages created by Setuptools, which are a common format used by third-party Python libraries and extensions, and. Egg files are really just. zip files that add additional metadata (such as version numbers, dependencies, and so on).

#要强调的: You can import only. py,.pyc files from a. zip file. Shared libraries and extension blocks written using C cannot be loaded directly from the. zip file (at this point the packaging system such as setuptools can sometimes provide a workaround), and loading files from. zip does not create. pyc or. pyo files, so be sure to create them beforehand to avoid loading modules that are degraded by performance.

Compiling python files

To increase the speed of loading modules, the Python interpreter caches the compiled version of each module in the __pycache__ directory, in the format: MODULE.VERSION.PYC. Ensures that the compiled results can coexist in multiple versions.
#python检查源文件的修改时间与编译的版本进行对比, this is an automatic process that requires recompilation if it expires. And the compiled module is platform Independent. So the same libraries can be shared between systems of different architectures, that is, PYC is a cross-platform bytecode, similar to Java. net. is performed by a Python virtual machine, but the content of the PYC is related to the Python version, and different versions of the compiled PYC file are different, 2.5 compiled PYC files cannot be executed on 3.5, and PYC files can be deserialized. Thus it is only used to increase the loading speed of the template, not to encrypt

The Python interpreter does not detect caching in the following two scenarios

#1 If the module is imported directly from the command line, this way, each import is recompiled and the compiled results are not stored (this should be the case with previous versions of python3.3)
Python-m spam.py

#2 If the source file does not exist, then the cached results will not be used, if you want to use the compiled results without the source file, the compiled result must be in the source directory
#注:

      • Module names are case-sensitive, foo.py and foo.py represent two modules
      • You can use the import statement to automatically compile files into. pyc files, specify run scripts in the command line or standard input, and do not generate such files, so we use the Compieall module to create. pyc files for all modules in a directory

Python--5, 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.