Import the python module to implement the functions you need

Source: Internet
Author: User
The module enables you to logically organize your Python code segments. Assigning relevant code to a module makes your code easier to use and understand. The module is also a Python object and has random name attributes for binding or reference. Simply put, a module is a file that saves Python code. The module can define functions, classes, and variables. The module can also contain executable code. The module enables you to logically organize your Python code segments.

Assigning relevant code to a module makes your code easier to use and understand.

The module is also a Python object and has random name attributes for binding or reference.

Simply put, a module is a file that saves Python code. The module can define functions, classes, and variables. The module can also contain executable code.

Example

Python code in a module called aname can be found in a file named aname. py. The following is a simple module support. py.

Def print_func (par ):

Print "Hello:", par

Import statement

To use a Python source file, you only need to execute the import statement in another source file. The syntax is as follows:

Import module1 [, module2 [,... moduleN]

When the interpreter encounters an import statement, the module will be imported in the current search path.

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

#! /Usr/bin/python

# Import Module

Import support

# Now you can call the functions contained in the module.

Support. print_func ("Zara ")

Output result of the above instance:

Hello: Zara.

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

From... Import statement

The from statement of Python allows you to import a specified part from the module to the current namespace. Syntax:

>>> From modname import name1 [, name2 [,... nameN]

For example, to import the function of the module fib, use the following statement:

>>> From fib import fig

This statement does not import the entire fib module into the current namespace. Instead, it only introduces the fiber-ACCI in fib to the global symbol table of the module that executes this declaration.

From... Import * statement

It is also feasible to import all the content of a module to the current namespace. you only need to use the following statement:

>>> From mod_name import *

This provides a simple way to import all projects in a module. However, such declarations should not be used too much.

Positioning module

When you import a module, the Python parser searches for the module location in the following order:

  • Current Directory

  • If it is not in the current directory, Python searches for each directory under the shell variable PYTHONPATH.

  • .

  • If none of them are found, Python will view the default path. In UNIX, the default path is/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 in a list. The syntax of PYTHONPATH is the same as that of the shell variable PATH.

In Windows, the typical PYTHONPATH is as follows:

Set PYTHONPATH = c: \ python20 \ lib;

In UNIX systems, the typical PYTHONPATH is as follows:

Set PYTHONPATH =/usr/local/lib/python

Namespace and scope

A variable is the name (identifier) of a matched object ). A namespace is a dictionary containing variable names (keys) and their corresponding objects (values.

A Python expression can access the variables in a local namespace and a global namespace. If a local variable and a global variable have the same name, the local variable overwrites the global variable.

Each function has its own namespace. The scope rules of class methods are the same as those of common functions.

Python intelligently guesses whether a variable is local or global. it assumes that any variable assigned a value in the function is local.

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

The global VarName expression tells Python that VarName is a global variable, so that Python will not find this variable in a local namespace.

For example, we define a variable money in the global namespace. We then assign values to the variable money in the function, and Python assumes that money is a local variable. However, we did not declare a local variable money before the access. The result is an UnboundLocalError error. This problem can be solved by canceling the comments of the global statement.

>>> #! /Usr/bin/python

>>> Money = 2000

>>> Def AddMoney ():

# Cancel the following comments if you want to correct the code:

# Global Money

Money = Money + 1

>>> Print Money

>>> AddMoney ()

>>> Print Money

Dir () function

The dir () function is a sorted string list with the name defined in a module.

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

>>> #! /Usr/bin/python

>>># Import the built-in math module

>>> Import math

>>> Content = dir (math)

>>> Print content;

Output result of the above instance:

['Doc', 'file', 'name', 'acs', 'ASIN', 'Ata ',

'Atan2', 'ceil ', 'cos', 'cosh', 'degrees', 'e', 'exp ',

Fabs, floor, fmod, frexp, hypot, ldexp, log ',

'Log10', 'modf', 'pi ', 'pow', 'radians', 'sin ',

'Sqrt ', 'Tan', 'tanh']

Here, the special string variable name points to the module name, and the file points to the imported file name of the module.

Globals () and locals () functions

Depending on the call location, the globals () and locals () functions can be used to return names in global and local namespaces.

If locals () is called within the function, all the names that can be accessed in the function are returned.

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

The return types of both functions are Dictionary. So the names can be extracted using the keys () function.

Reload () function

When a module is imported to a script, the code at the top layer of the module is executed only once.

Therefore, if you want to re-execute the code at the top layer of the module, you can use the reload () function. This function re-imports the previously imported modules. Syntax:

>>> Reload (module_name)

Here, module_name should be placed directly with the module name, rather than a string. For example, you want to overload 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 modules, sub-packages, and sub-packages.

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

>>> #! /Usr/bin/python

>>> Def Pots ():

Print "I'm Pots Phone"

Similarly, we have two other files that save different functions:

  • Phone/Isdn. py contains the function Isdn ()

  • Phone/G3.py contains function G3 ()

Now, create file init. py in the Phone directory:

  • Phone/init. py

To use all functions when importing Phone, you need to use an explicit import statement in init. py, as shown below:

>>> From Pots import Pots

>>> From Isdn import Isdn

>>> From G3 import G3

After you add the code to init. py, all these classes are available when you import the Phone package.

>>> #! /Usr/bin/python

>>> # Now import your Phone Package.

>>> Import Phone

>>> Phone. Pots ()

>>> Phone. Isdn ()

>>> Phone. G3 ()

Output result of the above instance:

I'm Pots Phone

I'm 3G Phone

I'm ISDN Phone

For example, we place only one function in each file, but you can place many functions. You can also define Python classes in these files and create a package for these classes.

The above is the details about the functions required for the python module import. For more information, see other related articles in the first PHP community!

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.