Python Module Basics

Source: Internet
Author: User

Concept: In Python, a. py file is called a module

Benefits:

1. Improved maintainability

2. Reusable

3. Avoid conflicting function names and variable names. Each module has a separate namespace, so functions and variables of the same name can exist in separate modules. So we're writing our own modules without having to think about names that conflict with other modules.

Module Type:

1. Built-in standard module (standard library). Execute help (' modules ') to view all Python's own modules list

2. Third party open source module, can be installed through the PIP Install Module name Network

3. Custom Modules

Import path of the module:

Module invocation:

Import Module # All modules are imported

the From module Import XX # Imports its small module from a module, such as: From random import randint (This method imports the module when used directly: Randint (  X,X) on the line, there is no need to add random. , because you have not imported the random module), this method can be used to import a number of small modules, the middle of a comma (",") on the line.

From module.xx.xx import xx as rename # Imports a small module (or the form of a folder) from a directory in the module, such as: from Django.core impor T handlers. As rename is to rename the imported module in your program, such as: Import multiprocessing as Mulpro after using Mulpro in your program. Just do it.

from module.xx.xx Import * # Imports all the small modules from the directory of the module, and later calls the small module will not have to increase the module prefix before the small module, such as: from Socket IM Port * in your program to call the socket's small module, directly write the name of the small module, the front does not need to add a socket. 。 Note: It is not recommended to import this way, it is possible that this little module name conflicts with the name of your program's variable or the small module name of other modules you import.

Note: Once the module is called, it is equivalent to executing the code in another py file, such as:

Import the py file you wrote:

Write your own import exercise. py file contents are as follows:

def sayhi (cmd):     Print ('hello', cmd) def Saybye (cmd):     Print ('bye', cmd)

Import the following:

In the import exercise above, if you change the. py file to:

def sayhi (cmd):     Print ('hello', cmd) def Saybye (cmd):     Print ('bye', cmd) sayhi ('abc')

Import import exercise. py This file will print "HEOLL,ABC" directly, since calling this module is equivalent to moving the code from top to bottom of this py file.

From the above import diagram can be seen, I import the time is specifically into the directory of the file to import, it is because when the import of Python will not go to the system to find the global search for the file you imported, if you enter a directory, it will be in this directory search and import, If you do not write the import directory, it will go to the default path to search, view the default path method:

Import Syssys.path # the code above will print out its default search path.  #  My Computer's search results:#  [' ', ' d:\\python\\lib\\idlelib ', ' d:\\python\\python36.zip ', ' D:\\python\\dlls ', ' d:\\python\\lib ', ' D:\\python ', ' d:\\python\\lib\\site-packages ', ' d:\\python\\lib\\ Site-packages\\chardet-3.0.4-py3.6.egg '   # The path in this list is looked from left to right, the first pair of quotation marks below is "current directory", so the default is to go from the current directory to find, if the current directory is not found, Look for it in turn .  Sys.path is a list, you can also use Sys.path.append () to add a path to it, but the path you import is only added in your program, In other programs inside the Sys.path is not, when you close the program, you can not take advantage of the path you added, that is, the path is a one-time, only in your program effective.

' D:\\python\\lib\\idlelib ', ' d:\\python\\python36.zip '
# ' D:\\python\\dlls ', ' d:\\python\\lib ', ' D:\\python ', # These are Python's own installation packages related to things
# site-packages  # All standard libraries, including your own installed third-party libraries

Note: Import module is imported into memory

Open Source Module installation method:

Https://pypi.python.org/pypi is the open source module Library of Python

Installation method:

1. Manual Installation: Enter the directory of the required installation module in CMD and enter in the command line: Python setup.py build

After the build succeeds, enter it at the command line: Python setup.py install

Note: Installed under Python's site-packages

2. Networked installation: Pip Install module name

3. Domestic Resources Download:

Packages: (Package)

When your module files are more and more, you need to partition the module files, such as the responsibility to interact with the data in a folder, the page interaction related to the folder.

Like above, a folder manages multiple module files, and this folder is called a package.

If I run manage.py and need to import views.py under the CRM file, because the CRM file is the same level as manage.py in the folder My_proj, you can import it as follows:

 from  Import views  # The number of files that need to be imported in the CRM layer, at the time of the import in the CRM after the number of points, such as: Crm.xx.xx.xxxviews.xx ()   

The above is the import method of Python3. Python2 when importing a self-write folder, you need to add an empty file in the imported folder named "__init__.py" (two underscores on each side of the INIT, INIT is the abbreviation for initiate (initialization)) so that the self-written folder becomes a package.

That is, Python2 only in the folder to add the "__inti__.py" This empty file, this folder will become a package, but Python3 add this "__init__.py" empty file does not matter, but in order to standardize, it is best to add.

Run the manage.py when imported under the CRM views.py, if views.py also need to import the configuration file My_proj settings.py, you can import as follows:

 from Import Settings  #  my_proj is config file settings.xx ()## So, when you add a path to an environment variable, you add the path to the program's main entry function (that is, manage.py), and it doesn't matter how many layers are in the same location as the imported module (for example, views.py), and when you import the file. 

Relative imports:

CD: is to return to the previous level folder

Cd.. \.. is to return to the top two layers of this: refers to the relative path

Or the above example, manage.py calls views.py, views.py need to call models.py in the same directory, import views.py in models.py cannot be written like this: import models. Because, the main function is manage.py, so just the path manage.py is added to the Os.path, so Python will only manage.py this layer to find models. Therefore, even if views.py and models.py are in the same directory, they cannot be imported directly.

To import a py file in the same directory, you can use the following notation:

 from  Import Module  # from . Indicates the current directory is imported. It's  called a relative import.

When it comes to relative imports, the folder corresponding to the package must be correctly viewed by the Python interpreter as a package, not as a normal folder. Responsible for the relative import of packages in Python without being seen as a package, and unable to take advantage of the nested relationships between bundles.

The folder is considered as a package by the Python interpreter to meet two conditions:

1. The file must have a __inti__.py file, which can be empty, but it must exist.

2. The py file in this folder cannot be executed as a top-level module (that is, it cannot be used as a portal for the main function). (relative imports cannot be relative to the program's root directory)

Note: Although Python supports relative import, it is not recommended to use it frequently (form) in the project because the path relationship between modules is more stringent and improper handling is error prone. Use a little more, from. Use less)

Python Module Basics

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.