Basic knowledge about modules in Python

Source: Internet
Author: User
This article mainly introduces the basic knowledge about the use of modules in Python, which is the basis for getting started with Python. If you need it, you can refer to the next module to organize Python code logically. Add the relevant code to a module to make the code easier to understand and use. A module is a Python object that can be bound to or referenced from any named attribute.

Simply put, a module is a file of Python code. A module can define functions, classes, and variables. The module can also contain executable code.
Example:

The module name of the Python code is aname. py. The following is a simple module with support. py as an example.

def print_func( par ):  print "Hello : ", par  return

Import Statement:

You can use any Python source file as a module by executing the import Statement in other Python source files. The import syntax is as follows:

import module1[, module2[,... moduleN]

When the interpreter encounters an import statement, it imports the (import) module if the module appears in the search path. The search path is a directory list, which is searched before being imported by the interpreter module. For example, to import the module hello. py, run the following command at the top of the script:

#!/usr/bin/python# Import module supportimport support# Now you can call defined function that module as followssupport.print_func("Zara")

When the above code is executed, the following results are generated:

Hello : Zara

A module is loaded once, regardless of the number of imports. This prevents multiple import operations by the module.
From... import Statement

The from Statement of Python can import specific attributes from a module to the current namespace. From... import Syntax:

from modname import name1[, name2[, ... nameN]]

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

from fib import fibonacci

This statement does not import the entire module fib to the current namespace; it only introduces the global symbol table columns of the fiber ACCI module fib import module.
From... import * Statement:

It can also use the following import statement to import all the names from the module to the current namespace:

from modname import *

This provides a simple way to import all projects from the module to the current namespace; however, this statement should be used with caution.
Positioning module:

When a module is imported, it is searched by the Python interpreter in the following sequence modules:

  • Current Directory
  • If this module is not found, search for each directory in the shell variable PYTHONPATH in Python.
  • If all these methods fail, Python checks the default path. On UNIX, the default path is/usr/local/lib/python/

The module search path is stored in the system module sys as the sys. path variable. The variables in sys. path contain the current directory, PYTHONPATH, and related default installation.
PYTHONPATH variable:

In PYTHONPATH, it is an environment variable, including the directory list. The shell variable PATH in PYTHONPATH is the same.

The following is a typical PYTHONPATH in Windows:

set PYTHONPATH=c:\python20\lib;

Here is the typical PYTHONPATH of UNIX systems:

set PYTHONPATH=/usr/local/lib/python

Namespace and scope:

The variable name (identifier) is mapped to the object. The namespace is the dictionary of the variable name (key) and its corresponding object (value.

Python statements can access variables in local namespaces and global namespaces. If the local and global variables have the same name, the local variables shield the global variables.

Each function has its own namespace. Class methods follow the same scope rules as common functions.

Python assumes that the variable is local or global. It assumes that the value of any variable value assignment function is partial.

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

Declaring global VarName indicates that Python VarName is a global variable. Python stops searching for the local namespace of the variable.

For example, we define the variable Money in the global namespace. Given the value of Money in the function, Python assumes that Money is a local variable. However, we set it, so an UnboundLocalError is the value of the local variable Money accessed before the result. Canceling the global statement solves this problem.

#!/usr/bin/pythonMoney = 2000def AddMoney():  # Uncomment the following line to fix the code:  # global Money  Money = Money + 1print MoneyAddMoney()print Money

Dir () function:

Use the dir () built-in function to return a sorting list of strings containing the names defined in a module.

The list contains the names of all modules, variables, and functions defined in a module. The following is a simple example:

#! /Usr/bin/python # Import built-in module mathimport mathcontent = dir (math) print content; when the above code is executed, the following results are generated: ['_ 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 ', 'sinh', 'sqrt ', 'tan', 'tanh']

Here, the special string variable _ name _ is the module name, __file _ is the file name of the module loaded from it.
Globals () and locals () functions:

The globals () and locals () functions can be used to return the names of global and local namespaces based on the locations they are called.

If locals () is called by a function, it returns all the names that can be accessed from the local function.

If globals () is called from a function, it returns all the names that can be accessed from the global function.

The return types of these two functions are dictionaries. Therefore, the name can be extracted using the keys () function.
Reload () function:

When the 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 top-level code module, you can use the reload () function. The reload () function imports the previously imported modules. The syntax of the reload () function is as follows:

reload(module_name)

Here, module_name is the name of the module to be reinstalled and does not contain the module name string. For example, to reload the hello module, perform the following operations:

reload(hello)

Packages in Python:

A package is a hierarchical file directory structure used to define a single Python application environment, such as modules, sub-packages, and sub-packages.

Consider that a file Pots. py is available in the Phone directory. The source code of this file is as follows:

#!/usr/bin/pythondef Pots():  print "I'm Pots Phone"

In a similar way, the other two files with different functions have the same name as above:

  • The Phone/Isdn. py file has the function Isdn ()
  • The Phone/G3.py file has the function G3 ()

Now, a file _ init _. py is added to the Phone directory:

 Phone/__init__.py

To make all functions available, when importing Phone, you need to specify the _ init _. py import Statement as follows:

from Pots import Potsfrom Isdn import Isdnfrom G3 import G3

After these rows are added to _ init _. py, all these classes of the Phone package have been imported.

#!/usr/bin/python# Now import your Phone Package.import PhonePhone.Pots()Phone.Isdn()Phone.G3()

When the above code is executed, the following results are generated:

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

In the preceding example, we use a single function for each file, but multiple functions can be retained. You can also define different Python classes in these files and create those classes outside the package.

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.