Module Introduction
Python offers a number of third-party modules that can be introduced, and the modules in the Python standard installation package are called standard libraries. The introduction of the module mainly has the following three kinds:
① Introduction Module
Import ModuleName
② functions under the introduction of modules
from import function1, function2,...
③ all functions introduced into the module
from Import *
The first way to introduce modules in the use of modules need to bring the module name (modulename.methodname), such as math.sqrt ();
After introducing the module, we can use the method in the module.
Example: Calculating the square root of 25
1 Import Math 2 r = math.sqrt (3)print R
If the module or function name is too long, you can use as to give the module a pseudonym after import, and then use the function in the module by using the kana. function.
Example:
1 Import WebBrowser as MyWeb 2 myweb.open_new_tab ("http://www.cnblogs.com/hyyq/")
use custom modules
example:
hello.py:
1 # Incoding:utf-8 2 def Hello (): 3 Print ' Import this module! ' 4 def Bokeyuan (): 5 Print ' http://www.cnblogs.com/hyyq/ '
test.py:
1 # Incoding:utf-8 2 Import # The file name is a module name and no suffix is required. py Oh ~ 3 Hello.hello () 4 Hello.bokeyuan ()
Output:
1 Import This module! 2 http://www.cnblogs.com/hyyq/
The above-mentioned program and module program need to be in the same directory, the limitations are very large. If you want the module to be referenced by any file, you can call Os.path.append (the directory where the module file is located) to add the directory of the module to the system.
Example: Assuming the file structure
~/| Module # folder module # call the ' Hello ' module program file #Hello folder # Module file # Module bytecode file
test.py:
# Incoding:utf-8 Import sys sys.path.append ('./hello'# Hello folder under current directory import # file name as module name, no suffix required. py ~Hello.hello () Hello.bokeyuan ()
This way of adding a file directory to the system is also limited and cumbersome to use. Generally, there are three ways to tell the Python interpreter where to find the module file:
Add module file path in ①pythonpath environment variable
②.pth file, the path of all module files is listed in the file (in the Python installation directory)
③ Module Packaging (recommended)