Summary of import or from usage in Python and usage of modules and packages

Source: Internet
Author: User

First, Introduction

1, module: According to the official Python explanation, the so-called module is a. py file, used to store variables, methods of the file, easy to import in other Python files (via import or from);


2, package: The package is a larger organizational unit, used to organize different management of multiple module files; Citing the official saying, "Suppose you want to design a module (package) to unify the collection of sound and sound data." There are many different sound file formats (example:. Wav,.aiff,.au,.mp3, etc.), so you may need to create and maintain a growing collection of modules to convert between various file formats. For sound data, you may also need to perform many different actions (such as mixing, adding echoes, applying the Equalizer function, creating an emulated stereo effect), so you will also write an endless stream of modules. At this point, you can have a possible structure (represented by a hierarchical file system) "


3. Import is used for importing modules (single file or package); The from is used to import a method (all or part) from a module (either a single file or a file module in a package) or as a method name for an as rename import.

Package Benefits: Whether through the import or from module (method) is the search path in the Sys.path to find, or the program runs the current directory. This search is linear, so if you have two module names, you cannot import both of the methods in the same name module.

Learned about the difference between package and module and import and from use. It is very helpful for us to see the source code project, and it is also easy for us to organize

Project code.

Hundred say better than a practice, the following example shows the difference between a package and a module when using import and from imports (references).


Second, the test environment to build

1, first of our experimental environment directory is as follows:

650) this.width=650; "title=" Selection _028.png "alt=" 7b571fe09d861804d1883b5c18559916.png-wh_ "src=" https://s3.51cto.com/ Oss/201711/10/7b571fe09d861804d1883b5c18559916.png-wh_500x0-wm_3-wmp_4-s_496742242.png "/>

Modesdir #顶层目录

-web #web包

-WEB2 #web2包

-__init__.py #web2包中的__init__. py file (the Python package must have __init__.py file function after that)

-hello.py #web2中的hello文件 (module)

-__init__.py #web包中的__init__. py file (module)

-logger.py #web包中的logger. py file (module)

-webtest.py #web包中的webtest. PY Module

-bin.py

-calculate.py

2, each package (code in the module)

#cat calculate.py

#coding: Utf-8print ("OK") _z = "Zz" x = 3def Add (x, y): return x + ydef sub (x, y): Return x-ydef Chen (x, y): Print (" From mod ") return x * y

#cat web/__init__.py

#coding: Utf-8print ("in Web1")

#cat web/logger.py

#coding: Utf-8def logger (): Print ("Logging.")


#cat web/webtest.py

#coding: Utf-8def webTest (): Print ("This is WEB2 test.")

#cat web/web2/__init__.py

#coding: Utf-8print ("in Web2")

#cat web/web2/hello.py

#coding: Utf-8def hi (): Print ("Hello world!")


III. module import for modules and packages

The main program is tested here under the bin.py of Modesdir.

To do the following tests:

1. Import calculate.py Single module file

Import calculate result = Calculate.add Print (result)

The results are as follows:

650) this.width=650; "title=" Selection _018.png "alt=" 00f62e3c28fbda5c192795acd8190379.png-wh_ "src=" https://s4.51cto.com/ Oss/201711/10/00f62e3c28fbda5c192795acd8190379.png-wh_500x0-wm_3-wmp_4-s_1348038719.png "/>

Note The above OK output, which indicates that the code in the module was executed from the import (top to bottom).

2. Importing modules from a Web package

Import Web.loggerweb.logger.logger ()

The results of the operation are as follows:

650) this.width=650; "title=" Selection _019.png "alt=" 034a9e0f5bd6fedc66c0800ada46e26b.png-wh_ "src=" https://s2.51cto.com/ Oss/201711/10/034a9e0f5bd6fedc66c0800ada46e26b.png-wh_500x0-wm_3-wmp_4-s_2382378352.png "/>

The output is more than one in web1 it is obvious that this is the __init__.py under the Web package being executed. So first, insert a sentence:

__init__.py: Used to do some initialization work for the package. Can be empty, but must have, mainly to prevent the difference of the same name of the directory, the official document that can be in __init__.py __all__ = [] in the module name. This is visible from the "package" Import *

The module is listed in __all__, otherwise the module is not visible. So here the in Web1 content is output.


3, import the module in the WEB.WEB2

Import Web.web2.helloweb.web2.hello.hi ()

Run results

650) this.width=650; "title=" Selection _020.png "alt=" 58637c8bc7622470b0275a05a5e34ef4.png-wh_ "src=" https://s3.51cto.com/ Oss/201711/10/58637c8bc7622470b0275a05a5e34ef4.png-wh_500x0-wm_3-wmp_4-s_5243767.png "/>

This is because the import of WEB.WEB2 two packets, so appear in the web1 in web2 content, can you see the role of __init__.py?

Test, so you can delete it.


What happens if I import a package directly (or a package under a package)?

4. Import Web.web2

Import Web.web2web.web2.hello.hi ()

Run

650) this.width=650; "title=" Selection _021.png "alt=" Bfd2c2f762a85a75528e30d776571717.png-wh_ "src=" https://s1.51cto.com/ Oss/201711/10/bfd2c2f762a85a75528e30d776571717.png-wh_500x0-wm_3-wmp_4-s_2312249464.png "/>

Something went wrong. Not found.

Conclusion:

Import imports can be "packages. modules or packages. N Packages. The module or Direct module" (in the current directory or SYS.PATH environment variable) cannot be a package without a module, in other words, must end with a module, whether it is in a package or a separate module file is invoked
Called with "[package.] Module. Method ("parameter") "This package is optional.


Iv. usage of the From

1. Import the Add function method from calculate

From calculate import addprint (add)

Run results

650) this.width=650; "title=" Selection _024.png "alt=" B60ff55241c649e79077755bb408db45.png-wh_ "src=" https://s5.51cto.com/ Oss/201711/10/b60ff55241c649e79077755bb408db45.png-wh_500x0-wm_3-wmp_4-s_1191826556.png "/>

The result of the run is consistent with the import call results from the previous section 31. However, the calling method is different, and the file name in the original module is called directly here.

2. Import the Logger function method from the Logger module from the Web package

From Web.logger import Loggerlogger ()

Run

650) this.width=650; "title=" Selection _025.png "alt=" B7a550b37f3459a0520c3cb17e132d58.png-wh_ "src=" https://s3.51cto.com/ Oss/201711/10/b7a550b37f3459a0520c3cb17e132d58.png-wh_500x0-wm_3-wmp_4-s_1527532117.png "/>

Consistent with import Web.logger.logger () in the previous section, 32.

3, from the Web (package). WEB2 (Package). Import Hi method in Hello Module

From Web.web2.hello import Hihi ()

Operation Result:

650) this.width=650; "title=" Selection _026.png "alt=" F5b3a45fe747a885d0e2be885b6778ab.png-wh_ "src=" https://s2.51cto.com/ Oss/201711/10/f5b3a45fe747a885d0e2be885b6778ab.png-wh_500x0-wm_3-wmp_4-s_2807331850.png "/>

Same and 3 Web.web2.hello.hi () results in the previous section.

4. From Calculate import *

From calculate import *print (_z)

Operation Result:

650) this.width=650; "title=" Selection _027.png "alt=" 9eaa0400f8a675d39ebb52ed0a627f9a.png-wh_ "src=" https://s4.51cto.com/ Oss/201711/10/9eaa0400f8a675d39ebb52ed0a627f9a.png-wh_500x0-wm_3-wmp_4-s_1148251187.png "/>

At this time the _z variable is not found, and the double underscore (non-double underline end) variable is not found!


5, __all__ = [] When the From package import *

From web Import *logger.logger () Webtest.webtest ()

Operation Result:

650) this.width=650; "title=" Selection _029.png "alt=" 30865f2076a0aebb50b866c7556bd741.png-wh_ "src=" https://s4.51cto.com/ Oss/201711/10/30865f2076a0aebb50b866c7556bd741.png-wh_500x0-wm_3-wmp_4-s_1280735065.png "/>

You can see that the WebTest module is not listed in the From Web import * Because of limitations in __all__. So here

Logger.logger () call succeeded, output logging. The WebTest module hints are not defined and cannot be found.


V. Summary

Through the above simulation package and module environment. The introduction of modules in packages and packages, separately referencing the methods in the module, is summarized in the test as follows:

When a module of the same name can exist in a different package, it must be imported in a package with import. Module. Method used.

The from import is the method under the (Package) module. It is possible to break a method with the same name in an existing namespace. and from the package import *

__all__ affected by __init__.py, the modules that are not listed are not able to import references. When the From module is import *, the private variables beginning with the Downline line _ are affected and cannot be referenced .

The above tests are available in both 2.x and 3.x, and the above code is passed under 3.5.2.

This article is from the "Learning, learning" blog, please be sure to keep this source http://dyc2005.blog.51cto.com/270872/1980753

Summary of import or from usage in Python and usage of modules and packages

Related Article

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.