Python Modules
In this article, you will learn to create and import custom modules in Python. Also, you will find different techniques to import and use custom and built-in modules in Python.
Table of Contents
- What are modules in Python?
- How to import modules in Python?
- Python Module Search Path
- Reloading a module
- The dir() built-in function
Python模块
在这篇文章里,你将学习创建和导入普通的模块。还有你将发现不同技术去导入和使用一般的,内置模块。
表格内容
- 什么是模块?
- 怎样导入模块?
- 导入语句
- 导入重命名
- from...导入语句
- 导入所有名
- 模块搜索路径
- 重新加载模块
- dir()内置函数
What are modules in Python?
Modules refer to a file containing Python statements and definitions.
A file containing Python code, for e.g.: example.py
, is called a module and its module name would be example
.
We use modules to break down large programs into small manageable and organized files. Furthermore, modules provide reusability of code.
We can define our most used functions in a module and import it, instead of copying their definitions into different programs.
什么是Python模块?
模块引用包含Python语法和定义的文件。
一个文件包含Python代码,例如:example.py是一个模块,它的模块名为example。
我们使用模块分解大型的程序为小块可管理和有组织的文件。此外,模块提高代码的可重复性。
我们可以定义我们最常使用的函数到一个模块,然后导入它,代替复制他们的定义导入不同程序。
Let us create a module. Type the following and save it as example.py
.
# Python Module example
def add(a, b):
"""This program adds two
numbers and return the result"""
result = a + b
return result
Here, we have defined a function add()
inside a module named example
. The function takes in two numbers and returns their sum.
让我们创建一个模块, 敲打以下内容保存它为example.py
# -*- coding:utf-8 -*-
def add(a,b):
"""这个程序2个数相加,返回他们的结果"""
result = a + b
return result
这里,我们有定义一个模块到函数add()里面。这函数接收2个数字并返回他们的和。
How to import modules in Python?
We can import the definitions inside a module to another module or the interactive interpreter in Python.
We use the import
keyword to do this. To import our previously defined module example
we type the following in the Python prompt.
>>> import example
This does not enter the names of the functions defined in example
directly in the current symbol table. It only enters the module name example
there.
Using the module name we can access the function using the dot .
operator. For example:
>>> example.add(4,5.5)
9.5
在Python中怎么导入模块?
我们可以吧一个模块里面的定义导入到另外模块或是Python交互式解释器中。
我们使用import关键字去做这些。以下我们在Python中敲下命令去导入我们以前定义的模块example。
>>> import example
在当前符合表,不需要直接输入在example里函数定义的名字。它仅仅输入模块名example名。
In [2]: import example
In [3]: example.add(4,5.5)
Out[3]: 9.5
Python has a ton of standard modules available.
You can check out the full list of Python standard modules and what they are for. These files are in the Lib directory inside the location where you installed Python.
Standard modules can be imported the same way as we import our user-defined modules.
There are various ways to import modules. They are listed as follows.
你可以查看Python完整列表的标准模块,他们是做什么的。这些文件是在本地库目录里在你安装Python的时候。
标准模块导入的方式和我们导入自定义的模块方式一样。
这里有各种各样导入模块的方式。他们如以下方式。
Python import statement
We can import a module using import
statement and access the definitions inside it using the dot operator as described above. Here is an example.
# import statement example
# to import standard module math
import math
print("The value of pi is", math.pi)
When you run the program, the output will be:
The value of pi is 3.141592653589793
Python导入语句
你可以导入一个模块使用import语句,访问它内部的定义使用点操作符如上所述。
这里也有一个例子。
当你运行程序是,结果输出:
In [4]: import math
In [5]: print("The value of pi is:",math.pi)
The value of pi is: 3.141592653589793
Import with renaming
We can import a module by renaming it as follows.
# import module by renaming it
import math as m
print("The value of pi is", m.pi)
We have renamed the math
module as m
. This can save us typing time in some cases.
Note that the name math
is not recognized in our scope. Hence, math.pi
is invalid, m.pi
is the correct implementation.
导入重命名
我们可以导入一个模块后重命名,如下。
In [7]: import math as m
In [8]: print("The value of pi is:",m.pi)
The value of pi is: 3.141592653589793
我们把math模块重命名为m。在一些例子里我们可以节省敲击代码的时间。
注意:名字math是不被识别的在我们的范围里。因此,math.pi是无效的,m.pi是正确的实现。
Python from...import statement
We can import specific names from a module without importing the module as a whole. Here is an example.
# import only pi from math module
from math import pi
print("The value of pi is", pi)
We imported only the attribute pi from the module.
In such case we don't use the dot operator. We could have imported multiple attributes as follows.
>>> from math import pi, e
>>> pi
3.141592653589793
>>> e
2.718281828459045
Python from...import语句
我们导入一个模块指定的名字没有导入整个模块。这样有一个例子。
In [11]: from math import pi
In [12]: print("The value of pi is:",pi)
The value of pi is: 3.141592653589793
我们仅从模块中导入属性pi。
像这样的例子我们不需要点号。以下例子我们可以导入多个属性。
In [14]: from math import pi,e
In [15]: pi
Out[15]: 3.141592653589793
In [16]: e
Out[16]: 2.718281828459045
Import all names
We can import all names(definitions) from a module using the following construct.
# import all names from the standard module math
from math import *
print("The value of pi is", pi)
We imported all the definitions from the math module. This makes all names except those beginnig with an underscore, visible in our scope.
Importing everything with the asterisk (*) symbol is not a good programming practice. This can lead to duplicate definitions for an identifier. It also hampers the readability of our code.
导入所有名字
使用以下结构我们可以从一个模块中导入所有名字(定义)。
In [19]: from math import *
In [20]: print("The value of pi is:",pi)
The value of pi is: 3.141592653589793
我们导入所有定义从math模块。这使所有的名字在除了以下划线开头的,都在我们作用域内可见。
导入所有使用星号(*)标识符不是一个好编程实践。这导致标识符定义的重复。它也对我们的代码可读性有害。
Python Module Search Path
While importing a module, Python looks at several places. Interpreter first looks for a built-in module then (if not found) into a list of directories defined in sys.path
. The search is in this order.
- The current directory.
PYTHONPATH
(an environment variable with a list of directory).- The installation-dependent default directory.
>>> import sys
>>> sys.path
['',
'C:\\Python33\\Lib\\idlelib',
'C:\\Windows\\system32\\python33.zip',
'C:\\Python33\\DLLs',
'C:\\Python33\\lib',
'C:\\Python33',
'C:\\Python33\\lib\\site-packages']
We can add modify this list to add our own path.
Python模块搜索路径
当我们正导入一个模块时,Python查看几个地方。解释器首先查找内置模块然后(如果找不到)进一步查找在sys.path定义的目录列表。这是搜索顺序。
- 当前目录
PYTHONPATH
(目录列表的环境变量)- 安装依赖的默认目录
>>> import sys
>>> sys.path
['',
'C:\\Python33\\Lib\\idlelib',
'C:\\Windows\\system32\\python33.zip',
'C:\\Python33\\DLLs',
'C:\\Python33\\lib',
'C:\\Python33',
'C:\\Python33\\lib\\site-packages']
我们可以添加修改这个列表来添加到我们的路径。
Reloading a module
The Python interpreter imports a module only once during a session. This makes things more efficient. Here is an example to show how this works.
Suppose we have the following code in a module named my_module
.
# This module shows the effect of
# multiple imports and reload
print("This code got executed")
Now we see the effect of multiple imports.
>>> import my_module
This code got executed
>>> import my_module
>>> import my_module
加载一个模板
Python解释器在会话期间模块导入只能用一次,这是很有效率的。这里有一个例子展示它怎样工作
假设我们在模板名为my_module有以下代码。
# This module shows the effect of
# multiple imports and reload
print("This code got executed")
现在我们看到多个次导入的效果。
>>> import my_module
This code got executed
>>> import my_module
>>> import my_module
We can see that our code got executed only once. This goes to say that our module was imported only once.
Now if our module changed during the course of the program, we would have to reload it.One way to do this is to restart the interpreter. But this does not help much.
Python provides a neat way of doing this. We can use the reload()
function inside the imp
module to reload a module. This is how its done.
>>> import imp
>>> import my_module
This code got executed
>>> import my_module
>>> imp.reload(my_module)
This code got executed
<module 'my_module' from '.\\my_module.py'>
我们可以看到我们的代码仅被执行一次。这也就是说我们的模块仅被导入一次。
现在如果我们模块在程序执行过程中改变,我们需要重新加载它。另外的方式是重新加载到解释器。但是这帮助不是很多。
Python提供一个简洁的方式。我们使用在imp模块里边的reload()函数重新导入模块。它是怎么做的。
>>> import imp
>>> import my_module
This code got executed
>>> import my_module
>>> imp.reload(my_module)
This code got executed
<module 'my_module' from '.\\my_module.py'>
The dir() built-in function
We can use the dir()
function to find out names that are defined inside a module.
For example, we have defined a function add()
in the module example
that we had in the beginning.
>>> dir(example)
['__builtins__',
'__cached__',
'__doc__',
'__file__',
'__initializing__',
'__loader__',
'__name__',
'__package__',
'add']
Here, we can see a sorted list of names (along with add
). All other names that begin with an underscore are default Python attributes associated with the module (we did not define them ourself).
dir()内置函数
我们使用dir()函数去查找出定义在模块里的名字。
例如:我们在开始时我们有定义在模块example里的add()函数。
>>> dir(example)
['__builtins__',
'__cached__',
'__doc__',
'__file__',
'__initializing__',
'__loader__',
'__name__',
'__package__',
'add']
For example, the __name__
attribute contains the name of the module.
>>> import example
>>> example.__name__
'example'
All the names defined in our current namespace can be found out using the dir()
function without any arguments.
>>> a = 1
>>> b = "hello"
>>> import math
>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'b', 'math', 'pyscripter']
例如:__name__属性包含模块的名字。
In [24]: import example
In [25]: example.__name__
Out[25]: 'example'
在我们当前命名空间里定义过的所有的名字可以使用不带任何参数的dir()函数找出。
>>> a = 1
>>> b = "hello"
>>> import math
>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'b', 'math', 'pyscripter']
Check out these examples to learn more:
- PREVIOUS
PYTHON GLOBAL KEYWORD - NEXT
PYTHON PACKAGE