python--Module--10

Source: Internet
Author: User
Tags stdin

Original blog, reprint please indicate the source--Zhou Xuewei http://www.cnblogs.com/zxouxuewei/

Python Module

The Python module, which is a python file that ends with a. Py, contains Python object definitions and Python statements.

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.

Modules can define functions, classes, and variables, and modules can also contain executable code.

Example

The following example is a simple module support.py:

support.py module:

""
  Return
Introduction of import Statement module

Once the module is well defined, we can use the import statement to introduce the module with the following syntax:

Import module1[, module2[,... Modulen]

For example, to reference the module math, you can use import math to introduce it at the very beginning of the file. When you call a function in the math module, you must refer to this:

Module name. function name

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 support.py, you need to place the command at the top of the script:

test.py File Code:  

#-*-coding:utf-8



Support.print_func ("runoob")

The result of the above example output:
Hello:runoob 

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:

 from ModName import name1[, name2[, ... Namen]]

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

 from fib import 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:

 from modname Import *

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

For example, we want to introduce all the things in the math module at once, with the following statements:

 from Math import *
Search Path

When you import a module, the Python parser's search order for the module location is:

    • 1. Current directory
    • 2. If it is not in the current directory, Python searches for each directory under the shell variable PYTHONPATH.
    • 3, if not found, Python will look 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:\python27\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 within 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/-*-coding:utf-8 -*-def addmoney ():   # To correct the code, uncomment the following:    Global Money    1 print 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 math content=dir (math) print content; The result of the above instance 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.

In a nutshell, a package is a folder, but a __init__.py file must exist under the folder, and the contents of the file can be empty. __int__.py is used to identify the current folder as a package.

Consider a runoob1.py, runoob2.py, __init__.py file under the package_runoob directory, test.py the code for the Test call package, with the following directory structure:

test.pypackage_runoob|-- __init__.py|-- runoob1.py|--runoob2.py Source code is as follows:

package_runoob/runoob1.py


#-*-coding:utf-8

" I ' m in Runoob1 "

package_runoob/runoob2.py


#-*-coding:utf-8

" I ' m in Runoob2 "

Now, in Package_runoob

Directory created under __init__.py: package_runoob/__init__.py


#-*-coding:utf-8
if ' __main__ '
' Run as Main program '
Else:
' Package_runoob Initialization '

Then we create test.py in the package_runoob sibling directory to invoke the Package_runoob Package

test.py


#-*-coding:utf-8


From

From

RUNOOB2 () above instance output result: Package_runoob Initialize i'm in runoob1i'm in Runoob2

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.

system-related information module: Import SYSSYS.ARGV is a list that contains all the command-line arguments.    Sys.stdout Sys.stdin Sys.stderr respectively represents the standard input output, the error output of the file object. Sys.stdin.readline () reads a line from the standard input sys.stdout.write ("a"screen Output a sys.exit (exit_code) Exit program Sys.modules is a dictionary that represents all the available module Sys.platform in the system to get running operating system environment SYS.P  Ath is a list that indicates all paths to find Module,package. Operating system-related calls and actions: Import Osos.environ A dictionary contains the mapping of environment variables os.environ["HOME"] can get the environment variable home value Os.chdir (dir) changes the current directory Os.chdir ('D:\\outlook'Note that Windows uses the Escape OS.GETCWD () to get the current directory Os.getegid () get the valid group ID os.getgid () get the Group ID os.getuid () Get the User ID Os.geteuid () To a valid user ID Os.setegid os.setegid () os.seteuid () Os.setuid () os.getgruops () Get user group Name list os.getlogin () get user login name O S.GETENV Get environment variable OS.PUTENV SET environment variable Os.umask set umask os.system (CMD) use system call, run cmd command built-in module (can be used directly without import) commonly used built-in functions: Help (obj) online, obj is any type callable (obj) to see if an obj can call repr (obj) like a function to get the representation string of obj, which can be used to reconstruct a copy of the object Eval_r ( STR) represents a valid Python expression that returns the expression dir (obj) to view the name hasattr visible in obj's name space (Obj,name) to see if there is a name in the name space of obj Getatt R (Obj,name) obtains a name SetAttr (Obj,name,value) in the name space of obj as a name in the name space of obj pointing to Vale, the object delattr (obj , name) removes a name VARs (obj) from the name space of obj to return an object name space. Use dictionary to indicate that locals () returns a local name space, using dictionary to represent globals () to return a global name space, using the dictionary representation of type (obj) to view an obj Type isinstance (obj,cls) View obj is not CLS instance Issubclass (SUBCLS,SUPCLS) View SUbcls is not supcls subclass ################## type conversion ################# #chr (i) converts an ASCII value into character ord (i) converts a character or Unicode character into ASCII numeric Oct (x) turns an integer x into an octal representation of the string hex (x) converts an integer x into a hexadecimal representation of the string str (obj) to get the string description of obj list (seq) convert a sequence to a list tuple     (seq) converts a sequence into a tuple dict (), Dict (list) into a dictionaryint(x) into an integerLong(x) Convert to a long intergerfloat(x) convert to a floating-point number Complex (x) to the plural max ( ...) to find the minimum of min (...)

python--Module--10

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.