Python Learning (14) module

Source: Internet
Author: User

Directory
    • Python Module
    • Import statement
    • From ... import statement
    • From ... import * statement
    • Positioning module
    • Pythonpath variable
    • Namespaces and variables
    • Dir () function.
    • Globals () and locals () functions
    • Reload () function
    • Packages in Python
Python Module

Modules allow you to logically organize your Python code snippets.

Assigning the relevant code to a module will make your code better and easier to understand.

The module is also a Python object, with a random name attribute used to bind or reference.

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.

Example

A python code in a module called Aname can usually be found in a file called aname.py. The following example is a simple module support.py.

def Print_func():print"Hello:",return      

Import statement

To use a Python source file, simply execute the import statement in another source file with the following syntax:

Import Module1[, module2[,... Modulen]     

When the interpreter encounters an import statement, the module is imported if it is in the current search path.

A search path is a list of all directories that an interpreter will search first. To import the module hello.py, you need to place the command at the top of the script:

#!/usr/bin/python#-*-coding:utf-8-*-# Importing Module Import# can now invoke the function contained in the module, support .  Print_func("Zara")         

The result of the above example output:

Hello:Zara 

A module will only be imported once, no matter how many times you execute the import. This prevents the import module from being executed over and over again.

From...import statements

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

Fromimport name1[, name2[,... Namen]]       

For example, to import the Fibonacci function of a module FIB, use the following statement:

Fromimport Fibonacci 

This declaration does not import the entire FIB module into the current namespace, it only introduces the Fibonacci individual in the FIB to the global symbol table of the module that executes the declaration.

from...import* statements

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

FromImport* 

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

Positioning module

When you import a module, the Python parser's search order for the module location 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 looks at the default path. Under UNIX, the default path is generally/usr/local/lib/python/.

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

Pythonpath variable

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

In Windows systems, the typical pythonpath are as follows:

Set PYTHONPATH=C:\python20\lib;     

In Unix systems, the typical pythonpath are as follows:

Set PYTHONPATH=/usr/local/lib/python      

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 in the local namespace and in the global namespace. If a local variable and a global variable have the same name, 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 intelligently guesses whether a variable is local or global, and assumes that any variable that is assigned within the function is local.

Therefore, if you want to assign a value to a global variable in a function, you must use the global statement.

The expression for global varname tells Python that VarName is 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 then 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 a local variable money before the visit, and the result is a unboundlocalerror error. Canceling the comment on the global statement will solve this problem.

#!/usr/bin/python#-*-Coding:utf-8-*- money = 2000 def addmoney ():  # want to correct the code, uncomment the following:  # global moneymoney = money  + 1  moneyaddmoney () print money       

Dir () function

The Dir () function is a well-ordered list of strings, and the content is a name defined in a module.

The returned list contains all the modules, variables, and functions defined in a module. Here is a simple example:

#!/usr/bin/python#-*-coding:utf-8-*-# Importing built-in math module import = dir(math)  Print content;          

The result of the above example output:

[' __doc__ ', ' __file__ ', ' __name__ ', ' ACOs ', ' ASIN ', ' Atan ', ' Atan2 ', ' Ceil ', ' Cos ', ' Cosh ', ' Degrees ', E, ' Exp ', ' Fabs ', ' Floor ', ' Fmod ', ' Frexp ', ' Hypot ',  ' ldexp ' ,  ' log ' , ' log10 ' , ' MODF ' ,  ' pi '   ' POW ' ,  ' radians ' ,  ' sin ' ,  Sinh ' ,  ' sqrt ' ,  ' tan ' ,  ' tanh '     

Here, the special string variable __name__ points to the name of the module, and __file__ points to the import file name of the module.

Globals () and locals () functions

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

If locals () is called inside the function, all the names that can be accessed 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 type of two functions is a dictionary. So names can be extracted with the keys () function.

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 part of the module, you can use the reload () function. The function will re-import the previously imported modules. The syntax is as follows:

Reload(module_name)  

Here, module_name to directly put the module's name, not a string form. For example, to reload the Hello module, as follows:

Reload(hello)  

Packages in Python

A package is a hierarchical file directory structure that defines a Python application environment consisting of a module and a sub-package, and a sub-package under a sub-package.

Consider a pots.py file in the phone directory. This file has the following source code:

#!/usr/bin/python#-*-coding:utf-8-*-defpots():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:

FrompotsimportPotsfromIsdnimportISDNfromimport 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 pack to the phone phone.  Pots()Phone.  Isdn()Phone.  G3()               

The result of the above example output:

I' m Pots phonei '3GphoneI' 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.

Python Learning (14) 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.