Import issues for Python packages and modules

Source: Internet
Author: User
Tags time 0

Module--Code encapsulation
Modules are the basic way to organize your code in Python. Python scripts are saved with a text file with the extension py, a script can be run alone, or it can be imported to run in another script, which we call Modules (module) when the script is imported and run. That is, all the code files we write in Python can be called modules.
When importing, the module name is the same as the file name of the script, for example, we write a script named items.py, then import it in another script with the import item statement.
See what modules are installed in Python in the Windows environment

>>> import sys >>> sys.modules  #windows环境下, import module mode: >> > IMPORT OS >>> OS.GETCWD ()   ' d:\\python33 '  >>>  os.chdir  (' F:\eclipse\workspace\learn\extend ')  >>> os.getcwd ()   ' f:\\eclipse\\ Workspace\\learn\\extend '  >>> import calculator 0.5 # Locate Python's working directory First OS.GETCWD ()   #然后改为当前工作目录os .chdir  (' F:\eclipse\workspace\learn\extend ')   #在F: \ Eclipse\workspace\learn\extend This directory has a previously written calculator file named calculator.py  #直接导入用import  calculator will be able to produce results.   #如果我导入上节课做的fibonacci螺旋递归代码   #那么一样进入用户交互  >>> import fibonacci3  Please enter Fibonacci spiral Layer:8  Note: Two numbers cannot be at the same time 0!   First digit 2.6  second digit -2.12 2.60 -2.12 0.48 -1.64 -1.16 -2.80 -3.96  -6.76 >>>

So write it in the editor.

Print (' This is the module that is running the import ') Import Fibonacci3 #运行结果: This is the module in which you are running the import Fibonacci Spiral Layer: 6 Note: Two digits cannot be 0! First digit 2.2 second number 0.95 2.20 0.95 3.15 4.10 7.25 11.35
Print (' This is the module that is running the import ') Import Calculator3 #运行结果: This is the module that is running import 1.5

So look at the source code of calculator3.py:

From __future__ Import Division def f (x,o,y): print ({' + ': x+y, '-': X-y, ' * ': x*y, '/': X/y}.get (O)) F (3, '/', 2)

There has been an operation in it, so the import is directly the result of the output. If we remove the operation, that's the rest of the code.

From __future__ Import Division def f (x,o,y): print ({' + ': x+y, '-': X-y, ' * ': x*y, '/': X/y}.get (o))

So when we import this module again, there is only one function left, which requires an extra call. Call the method (create a new mol.py file):

Print (' This is the module that is running the import ') Import Calculator3 calculator3.f (3, '/', 2) #注意, the method that invokes the module function is the module name. function name (parameter value) #运行结果 This is the module that is running the import 1.5

Here's a question, if my module contains function assignment calculations, such as:

From __future__ Import Division def f (x,o,y): print ({' + ': x+y, '-': X-y, ' * ': x*y, '/': X/y}.get (O)) F (3, ' * ', 2)

Then I have two results when I run the mol.py file again:


This is the module that is running the import 6 1.5

The first result 6 is the result of the operation of the module itself, and the second 1.5 is the result of invoking the function of the module in mol.py.
in practical applications, there are two scenarios to consider.
the first is to directly execute the module file, the inside of the operation is required to execute.
The second is that if it is called by someone else, then the operational procedures in the module are not required to execute
The workaround is to use a built-in property and now add a line in calculator3.py:


From __future__ Import Division def f (x,o,y): print ({' + ': x+y, '-': X-y, ' * ': x*y, '/': X/y}.get (o)) print (__name__) #这 A __name__ is a built-in function, and the value of __name__ varies with the object being called #如果我们直接运行: __main__ #这是这个文件的对象名, probably means that we are now calling the main program (guessed by the tutorial) #我们在mol. PY Call Print (' This is the module that is running the import ') Import Calculator3 calculator3.f (3, '/', 2) #运行结果: This is the module that is running the import Calculator3 #这里__name__的值变成了文件名

1.5

Therefore, you can add a judgment in calculator3.py, when __name__ ==__main__ the execution of the source file operation program,
Otherwise, the function assignment operation that runs the module call is run.

from __future__ import division def f (x,o,y):  print ({' + '  : x+y,  '-'  : x-y, ' * '  : x*y,  '/'  : x/y}.get (o)  if __name__ ==  ' __main__ ':  f (3, ' * ', 2)   #那么直接运行calculator3. PY will do  f (3, ' * ', 2)   operations, while running in mol.py will not operate:  Print (' This is the module that is running the import ')  import calculator3 calculator3.f (3,  '/',  2)   #运行结果:  This is the module that is running the import  1.5 

When importing the module, there is a sequential limit, generally find the module file from the current directory, and then find  
string module is a built-in module, If I create a new file called string.py in the current directory, if you want to use the string built-in function after import, then the program will look for the string in the directory, the new string.py will be imported, the execution of the string built-in function will be an error. Therefore, to use the string module, you must delete the newly created string.py file and delete a file called String.pyc that was generated when you just imported it. To correctly use the built-in module of string

package  
python module can be organized by directory as a package  
1. Create a folder with the name of the package, 
2. Create a __init__.py file under this folder,  
3. Place script files, compiled extensions, and child packages  
4. Import pack.m1, pack.m2, pack.m3

, as needed


Demo: Create a new pack.py file, if we want to reuse the function operation in calculator3.py, then you can create a new folder in the directory where the calculator3.py is located, if the name For bag, create a new __init__.py file in the Bag folder (must have), the content can be empty, the need to import the calculator3.py file to copy into. Then this Bag folder can be called a Python package. Note that the py file of the calling module cannot be in the package, If the new pack.py here can not be placed in bag, otherwise will be error.  
file structure  
650) this.width=650, "title=" QQ picture 20140302212938 "border=" 0 "alt=" QQ picture 20140302212938 "Src=" http://images.cnitblog.com/ Blog/608216/201403/022148444851095.jpg "width=" 195 "height=" "style=" margin:0px auto;padding:0px;border:0px; Background-image:none; "/>

Print (' This is running the imported Python package ') import Bag.calculator3 #注意格式, package name. Module name BAG.CALCULATOR3.F (3, '/', 2) #调用函数时候 package name. Module name. function name (parameter value) # Run Result: This is the Python package that runs the import 1.5

Summary:
Module Import has import,import As,from import and several other methods. Specific differences of reference:
Http://www.cnblogs.com/allenblogs/archive/2011/11/15/2055149.html


Import issues for Python packages and modules

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.