Python's modules

Source: Internet
Author: User

The module allows us to use Python code more logically and effectively, assigning the relevant code to a module to make your code better and easier to understand, and of course the module is also a Python object with random names and attributes for binding or referencing. Simply put, the module is a file that holds the Python code. Modules can define functions, classes, and variables. The module can also contain executable code.


First, import statements

If you want to use a Python source file, you only need to execute the import statement in another file, with the following syntax:

Import module1[,module[,... Modulen]]

When the interpreter encounters an import statement, it searches the module for the current path and then imports it. The search path is a list of all the directories that an interpreter will search first, (in other words, the path to the search is a list, which contains various paths, and of course the path is defined by Python by default) if you want to import the module hello.py, you need to put the command at the top of the script:

For example:

[email protected] pass]# cat support.py#!/usr/bin/env python#-*-coding:utf8-*-def print_func (PAR): print "Hello: ", par return[[email protected] pass]# [[email protected] pass]# cat test.py #!/usr/bin/env python#-*-Coding:utf8-*-# Importing module Import support# can now invoke the functions contained in the module Support.print_func ("Zara") [[email protected] pass] #运行test. py script [[email protected] pass]# python test.py hello:zara[[email protected] pass]#

Note: When the module name is imported, the module file suffix must end with a. PY, otherwise import module name fails

[[email protected] pass]# ls

support.py test.py

[email protected] pass]# python test.py

Hello:zara

[Email protected] pass]# MV support.py support

[[email protected] pass]# ls

Support Support.pyc test.py

[Email protected] pass]# RM SUPPORT.PYC

Rm:remove regular file ' Support.pyc '? Y

[[email protected] pass]# ls

Support test.py

[Email protected] pass]# python test.py

Traceback (most recent):

File "test.py", line 4, <module>

Import support

Importerror:no module named support

[Email protected] pass]#


Second, From...import statement

The FROM statement of Python lets you import a specified section from the module into the current namespace. The syntax is as follows:

From modename import name1[,name2[,name3[... Namen]]

For example, to import the Fibonacci function in a module's FIB, use the following statement:

From fib import Fibonacci

This declaration does not import the entire FIB module into the current command space, it only introduces the Fibonacci single function in the FIB into the global symbol table of the module that executes the declaration.


Third, From...import * statement

It is also possible to import all the contents of a module into the current namespace, just use the following declaration:

From ModName Import *

Here is an easy way to import all the items in a module. However, such statements should not be used too much.


Four, positioning module

When importing a module, the Python interpreter's search order for the location of the module is:

① current Directory

② if it is not in the current directory, Python searches for each directory under the shell variable Pythonpath

③ If none are found, Python will look at the default path. Under UNIX, the default path is typically/usr/local/lib/python

The module search path is stored in the Sys.path variable of the system module. The variables contain the current directory, the directory that the Pythonpath variable contains, and the default directory that is determined by the installation process.

The path variable under system:

>>> import sys>>> sys.path[', '/usr/local/lib/python2.7/site-packages/ Setuptools-0.6c11-py2.7.egg ', '/usr/local/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg ', '/usr/local/lib/ Python27.zip ', '/usr/local/lib/python2.7 ', '/usr/local/lib/python2.7/plat-linux2 ', '/usr/local/lib/python2.7/ Lib-tk ', '/usr/local/lib/python2.7/lib-old ', '/usr/local/lib/python2.7/lib-dynload ', '/usr/local/lib/python2.7/ Site-packages ']>>> type (sys.path) <type ' list ' >>>>

From the above can be obtained, the value of the Sys.path variable is a list, each element of the list is a path, the list holds the Python interpreter's search path to the module, which is the current directory of the module, the directory of Pythonpath and the default directory of Python.


V. Pythonpath variables


As an environment variable, Pythonpath consists of many directories that are installed in a single list. The Pythonpath statement is the same as the shell variable path:

In the Windows environment, the typical pythonpath are as follows:

Set Pythonpath=c:\python20\lib;

In Unix (including Linux) environments, the typical pythonpath are as follows:

Export Pythonpath=/usr/local/lib/python

Or

Set Pythonpath=/usr/local/lib/python

Vi. Namespaces and Scopes

A variable is a name (identifier) that has a matching object. A namespace is a dictionary that contains the variable names (keys) and their respective objects (values).

A Python expression can access variables for both the local namespace and the global namespace. If a variable has the same name as a global variable, the local variable overrides the global variable.

Each function has its own namespace. The scope rules of a method of a class are the same as the usual functions.

Python will intelligently guess whether a variable is local or global, and it assumes that any variable that is assigned within the function is local, so if you want to assign a value to a global variable in a function, you must use the Global keyword (statement)

The global varname expression tells Python,varname to be a global variable so that Python does not look for the variable in the local namespace. For example, we define a variable money in the global namespace, we assign a value to the variable money within the function, and then Python assumes that money is a local variable. However, we did not declare the variable money before the visit, resulting in a unboundlocalerror error. Canceling the comment on the global statement will solve this problem.

The sample code is as follows:

#!/usr/bin/env python#-*-Coding:utf8-*-money = 2000def Addmoney (): #想改正代码就取消以 * * * Release: #global Money money = money + 1print Moneyaddmoney () print money
[email protected] pass]# python test002.py 2000Traceback (most recent call last): File ' test002.py ', line 9, in <m Odule> Addmoney () File "test002.py", line 7, in Addmoney money = money + 1unboundlocalerror:local variable ' Mon EY ' referenced before Assignment[[email protected] pass]#

Uncomment here (#global money)

#!/usr/bin/env python#-*-Coding:utf8-*-money = 2000def Addmoney (): #想改正代码就取消以 * * * Release: Global Money money = money + 1print Moneyaddmoney () print money
[[email protected] pass]# python test002.py 20002001[[email protected] pass]#


Vii.. Dir () function

The Dir () function is a well-ordered list of strings with names defined in a module

The returned list contains all the modules, variables, and functions defined in a module, such as the following:

#!/usr/bin/env python#-*-Coding:utf8-*-#导入math模块import mathcontent = dir (math) print content;
[[email protected] pass]# python test003.py [' __doc__ ', ' __file__ ', ' __name__ ', ' __package__ ', ' ACOs ', ' acosh ', ' asin ', ' a  Sinh ', ' atan ', ' atan2 ', ' Atanh ', ' ceil ', ' copysign ', ' cos ', ' cosh ', ' degrees ', ' e ', ' Erf ', ' erfc ', ' exp ', ' expm1 ', ' fabs ', ' Factorial ', ' floor ', ' fmod ', ' frexp ', ' fsum ', ' gamma ', ' hypot ', ' isinf ', ' isNaN ', ' ldexp ', ' lgamma ', ' Log ', ' log10 ', ' Lo g1p ', ' modf ', ' pi ', ' pow ', ' radians ', ' sin ', ' sinh ', ' sqrt ', ' tan ', ' tanh ', ' trunc '][[email protected] pass]#

Note: Here, the special string variable __name__ is the name of the module, __file__ the import file name that points to the module


Viii. Globals () and locals () functions

Depending on where they are called, the Globals () and locals () functions can be used to return names in global and local namespaces.

If you call locals () inside a function, all the names that are accessible in the function are returned.

If Globals () is called inside the function, all the global names that can be accessed in the function are returned.

The return of two functions is a dictionary. So the name can be obtained using the keys () function.


Nine, reload () function

When a module is imported into a script, the code at the top-level part of the module is executed only once. Therefore, if you want to re-execute the code in the top-level section of the module, you can use the reload () function, which will re-import the previously imported module with the following syntax:

Reload (module_name)

Here, module_name to directly put the module's name, not a string form, such as you want to overload the Hello module, as follows:

Reload (Hello)

Ix. packages in Python

Package is a hierarchical file directory structure, it defines a module and sub-package, hehe sub-package, such as the sub-package of the Python application environment.

Consider a pots.py file in the phone directory, which has the following code:

#!/usr/bin/python#-*-coding:utf-8-*-def pots (): print "I ' m pots Phone"

In the same way, we have two other files that hold different functions:

phone/isdn.py contains function Isdn ()

phone/g3.py contains function G3 ()

Now, create the file __init__.py in the phone directory:

phone/__init__.py

When you import the phone, in order to be able to use all the functions, you need to use explicit import statements in __init__.py, as follows:

From Pots import potsfrom Isdn import isdnfrom G3 import G3

When you add the code to __init__.py, the classes are all available when you import the phone package.

#!/usr/bin/python#-*-coding:utf-8-*-# import the phone package import phone phone.pots () phone.isdn () phone.g3 ()

The result of the above example output:

I ' m Pots phonei ' m 3G phonei ' m ISDN Phone

As above, for example, we only put a function in each file, but in fact you can put a lot of functions. You can also define Python classes in these files, and then build a package for those classes.


This article from "Flat Light is true" blog, please be sure to keep this source http://cryan.blog.51cto.com/10837891/1727310

Python's 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.