Python 简明教程

Python - Modules

Python Modules

Python 中 module 的概念进一步提高了模块化。你可以一起定义多个相关的函数并加载所需的函数。模块是一个包含函数定义的文件, classesvariables 、常量或任何其他 Python 对象。此文件的内容可以供任何其他程序使用。Python 有 import 关键字用于此目的。

The concept of module in Python further enhances the modularity. You can define more than one related functions together and load required functions. A module is a file containing definition of functions, classes, variables, constants or any other Python object. Contents of this file can be made available to any other program. Python has the import keyword for this purpose.

Example of Python Module

import math
print ("Square root of 100:", math.sqrt(100))

它将生成以下 output

It will produce the following output

Square root of 100: 10.0

Python Built-in Modules

Python 的标准库附带了大量模块。它们被称为内置模块。大多数这些内置模块是用 C 编写的(因为 Python 的参考实现是 C),并且预编译到库中。这些模块封装了有用的功能,如特定于系统操作系统的管理、磁盘 IO、网络等。

Python’s standard library comes bundled with a large number of modules. They are called built-in modules. Most of these built-in modules are written in C (as the reference implementation of Python is in C), and pre-compiled into the library. These modules pack useful functionality like system-specific OS management, disk IO, networking, etc.

以下是内置模块的选择列表 -

Here is a select list of built-in modules −

Python User-defined Modules

带有 .py 扩展名的任何文本文件和包含 Python 代码的文本文件基本上都是一个模块。它可以包含一个或多个函数、变量、常量的定义以及类。来自模块的任何 Python 对象都可以通过 import 语句在解释器会话或另一个 Python 脚本中使用。模块还可以包含可运行的代码。

Any text file with .py extension and containing Python code is basically a module. It can contain definitions of one or more functions, variables, constants as well as classes. Any Python object from a module can be made available to interpreter session or another Python script by import statement. A module can also include runnable code.

Creating a Python Module

创建模块只不过是用任何编辑器的帮助保存 Python 代码。让我们将以下代码保存在 mymodule.py

Creating a module is nothing but saving a Python code with the help of any editor. Let us save the following code as mymodule.py

def SayHello(name):
   print ("Hi {}! How are you?".format(name))
   return

您现在可以在当前 Python 终端中导入 mymodule。

You can now import mymodule in the current Python terminal.

>>> import mymodule
>>> mymodule.SayHello("Harish")
Hi Harish! How are you?

您还可以在另一个 Python 脚本中导入一个模块。将以下代码保存在 example.py 中

You can also import one module in another Python script. Save the following code as example.py

import mymodule
mymodule.SayHello("Harish")

从终端命令行运行此脚本

Run this script from command terminal

Hi Harish! How are you?

The import Statement

在 Python 中, import 关键字用于从一个模块加载 Python 对象。该对象可以是函数、类、变量等。如果一个模块包含多个定义,则所有这些定义都将被加载到名称空间中。

In Python, the import keyword has been provided to load a Python object from one module. The object may be a function, class, a variable etc. If a module contains multiple definitions, all of them will be loaded in the namespace.

让我们将具有三个函数的下列代码保存为 mymodule.py.

Let us save the following code having three functions as mymodule.py.

def sum(x,y):
   return x+y

def average(x,y):
   return (x+y)/2

def power(x,y):
   return x**y

import mymodule 语句加载这个模块中的所有函数到当前名称空间中。导入模块中的每个函数都是这个模块对象的属性。

The import mymodule statement loads all the functions in this module in the current namespace. Each function in the imported module is an attribute of this module object.

>>> dir(mymodule)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'average', 'power', 'sum']

要调用任何函数,请使用模块对象的引用。例如,mymodule.sum()。

To call any function, use the module object’s reference. For example, mymodule.sum().

import mymodule
print ("sum:",mymodule.sum(10,20))
print ("average:",mymodule.average(10,20))
print ("power:",mymodule.power(10, 2))

它将生成以下 output

It will produce the following output

sum:30
average:15.0
power:100

The from …​ import Statement

import 语句将会加载模块的所有资源到当前名称空间中。可以通过使用此语法从模块中导入特定对象。例如 −

The import statement will load all the resources of the module in the current namespace. It is possible to import specific objects from a module by using this syntax. For example −

mymodule 中的三个函数中,只有两个被导入到以下可执行脚本 example.py

Out of three functions in mymodule, only two are imported in following executable script example.py

from mymodule import sum, average
print ("sum:",sum(10,20))
print ("average:",average(10,20))

它将生成如下输出:

It will produce the following output −

sum: 30
average: 15.0

注意,不需要通过给函数加上其模块名前缀来调用它。

Note that function need not be called by prefixing name of its module to it.

The from…​import * Statement

还可以通过使用以下 import 语句将模块中的所有名称导入到当前名称空间中 −

It is also possible to import all the names from a module into the current namespace by using the following import statement −

from modname import *

这提供了一种将模块中的所有项导入当前名称空间的简单方法;但是,此语句应该谨慎使用。

This provides an easy way to import all the items from a module into the current namespace; however, this statement should be used sparingly.

The import …​ as Statement

您可以为导入的模块指定一个别名。

You can assign an alias name to the imported module.

from modulename as alias

调用时 alias 应该加在函数前面。

The alias should be prefixed to the function while calling.

看看以下 example

Take a look at the following example

import mymodule as x
print ("sum:",x.sum(10,20))
print ("average:", x.average(10,20))
print ("power:", x.power(10, 2))

Locating Modules

当你导入模块时,Python 解释器按以下顺序搜索模块 −

When you import a module, the Python interpreter searches for the module in the following sequences −

  1. The current directory.

  2. If the module isn’t found, Python then searches each directory in the shell variable PYTHONPATH.

  3. If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/.

模块搜索路径存储在系统模块 sys 中,作为 sys.path 变量。sys.path 变量包含当前目录、PYTHONPATH 和与安装相关的默认值。

The module search path is stored in the system module sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the installation-dependent default.

The PYTHONPATH Variable

PYTHONPATH 是一个环境变量,包括目录列表。PYTHONPATH 的语法与 shell 变量 PATH 相同。

The PYTHONPATH is an environment variable, consisting of a list of directories. The syntax of PYTHONPATH is the same as that of the shell variable PATH.

这是 Windows 系统中的典型 PYTHONPATH −

Here is a typical PYTHONPATH from a Windows system −

set PYTHONPATH = c:\python20\lib;

这是 UNIX 系统中的典型 PYTHONPATH −

And here is a typical PYTHONPATH from a UNIX system −

set PYTHONPATH = /usr/local/lib/python

Namespaces and Scoping

变量是映射到对象的名称(标识符)。命名空间是由变量名称(键)及其对应对象(值)组成的字典。

Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and their corresponding objects (values).

  1. A Python statement can access variables in a local namespace and in the global namespace. If a local and a global variable have the same name, the local variable shadows the global variable.

  2. Each function has its own local namespace. Class methods follow the same scoping rule as ordinary functions.

  3. Python makes educated guesses on whether variables are local or global. It assumes that any variable assigned a value in a function is local.

  4. In order to assign a value to a global variable within a function, you must first use the global statement.

  5. The statement global VarName tells Python that VarName is a global variable. Python stops searching the local namespace for the variable.

Example

例如,我们在全局命名空间中定义了一个变量 Money。在函数 Money 中,我们为 Money 赋值,因此 Python 假定 Money 是局部变量。但是,我们在设置局部变量 Money 的值之前访问了它的值,因此导致 UnboundLocalError。取消对 global 语句的注释可以解决该问题。

For example, we define a variable Money in the global namespace. Within the function Money, we assign Money a value, therefore Python assumes Money as a local variable. However, we accessed the value of the local variable Money before setting it, so an UnboundLocalError is the result. Uncommenting the global statement fixes the problem.

Money = 2000
def AddMoney():
   # Uncomment the following line to fix the code:
   # global Money
   Money = Money + 1

print (Money)
AddMoney()
print (Money)

Module Attributes

在 Python 中,模块是模块类的一个对象,因此它以属性为特征。

In Python, a module is an object of module class, and hence it is characterized by attributes.

以下为模块属性 −

Following are the module attributes −

  1. file returns the physical name of the module.

  2. package returns the package to which the module belongs.

  3. doc returns the docstring at the top of the module if any

  4. dict returns the entire scope of the module

  5. name returns the name of the module

Example

假设以下代码已保存为 mymodule.py

Assuming that the following code is saved as mymodule.py

"The docstring of mymodule"
def sum(x,y):
   return x+y

def average(x,y):
   return (x+y)/2

def power(x,y):
   return x**y

让我们导入以下脚本中的 mymodule 来检查其属性−

Let us check the attributes of mymodule by importing it in the following script −

import mymodule

print ("__file__ attribute:", mymodule.__file__)
print ("__doc__ attribute:", mymodule.__doc__)
print ("__name__ attribute:", mymodule.__name__)

它将生成以下 output

It will produce the following output

__file__ attribute: C:\math\examples\mymodule.py
__doc__ attribute: The docstring of mymodule
__name__ attribute: mymodule

The _name_Attribute

Python 模块的 name 属性非常重要。让我们详细了解一下。

The name attribute of a Python module has great significance. Let us explore it in more detail.

在交互式 shell 中, name 属性会返回“ main

In an interactive shell, name attribute returns 'main'

>>> __name__
'__main__'

如果你在解释器会话中导入任何模块,它会返回模块的名称作为该模块的 name 属性。

If you import any module in the interpreter session, it returns the name of the module as the name attribute of that module.

>>> import math
>>> math.__name__
'math'

从 Python 脚本内部, name 属性会返回“ main

From inside a Python script, the name attribute returns 'main'

#example.py
print ("__name__ attribute within a script:", __name__)

在命令终端中运行此代码−

Run this in the command terminal −

__name__ attribute within a script: __main__

此属性允许将 Python 脚本用作可执行文件或模块。与 C++、Java、C# 等不同,在 Python 中,不存在 main() 函数的概念。带 .py 扩展名的 Python 程序脚本可以包含函数定义以及可执行语句。

This attribute allows a Python script to be used as executable or as a module. Unlike in C++, Java, C# etc., in Python, there is no concept of the main() function. The Python program script with .py extension can contain function definitions as well as executable statements.

保存 mymodule.py 及其以下代码−

Save mymodule.py and with the following code −

"The docstring of mymodule"
def sum(x,y):
   return x+y

print ("sum:",sum(10,20))

你可以看到 sum() 函数在其被定义的同一脚本中被调用。

You can see that sum() function is called within the same script in which it is defined.

sum: 30

现在让我们在另一个脚本 example.py 中导入此函数。

Now let us import this function in another script example.py.

import mymodule
print ("sum:",mymodule.sum(10,20))

它将生成以下 output

It will produce the following output

sum: 30
sum: 30

输出 “sum:30” 出现了两次。一次是在导入 mymodule 模块时。导入模块中的可执行语句也会运行。第二个输出来自调用脚本,即 example.py 程序。

The output "sum:30" appears twice. Once when mymodule module is imported. The executable statements in imported module are also run. Second output is from the calling script, i.e., example.py program.

我们希望看到的是当导入模块时,只导入函数,而不运行其可执行语句。这可以通过检查 name 的值来完成。如果它是 main ,则表示它正在运行,未导入。有条件地包含函数调用等可执行语句。

What we want to happen is that when a module is imported, only the function should be imported, its executable statements should not run. This can be done by checking the value of name. If it is main, means it is being run and not imported. Include the executable statements like function calls conditionally.

mymodule.py 中添加 if 语句,如图所示−

Add if statement in mymodule.py as shown −

"The docstring of mymodule"
def sum(x,y):
   return x+y

if __name__ == "__main__":
   print ("sum:",sum(10,20))

现在,如果你运行 example.py 程序,你会发现 sum:30 输出只出现了一次。

Now if you run example.py program, you will find that the sum:30 output appears only once.

sum: 30

The dir( ) Function

内置函数 dir() 返回一个排序的字符串列表,其中包含模块定义的名称。

The dir() built-in function returns a sorted list of strings containing the names defined by a module.

该列表包含模块中定义的所有模块、变量和函数的名称。以下是一个简单的示例 −

The list contains the names of all the modules, variables and functions that are defined in a module. Following is a simple example −

# Import built-in module math
import math

content = dir(math)
print (content)

执行上述代码后,将生成以下结果 −

When the above code is executed, it produces the following result −

['__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']

The reload() Function

有时,你可能需要重新加载模块,尤其是在使用 Python 的交互式解释器会话时。

Sometimes you may need to reload a module, especially when working with the interactive interpreter session of Python.

假设我们有一个测试模块 (test.py),其中有以下函数−

Assume that we have a test module (test.py) with the following function −

def SayHello(name):
   print ("Hi {}! How are you?".format(name))
   return

我们可以导入该模块并从 Python 提示符调用其函数,如下所示−

We can import the module and call its function from Python prompt as −

>>> import test
>>> test.SayHello("Deepak")
Hi Deepak! How are you?

但是,假设你需要修改 SayHello() 函数,比如−

However, suppose you need to modify the SayHello() function, such as −

def SayHello(name, course):
   print ("Hi {}! How are you?".format(name))
   print ("Welcome to {} Tutorial by TutorialsPoint".format(course))
   return

即使编辑 test.py 文件并保存它,内存中加载的函数也不会更新。你需要重新加载它,使用 imp 模块中的 reload() 函数。

Even if you edit the test.py file and save it, the function loaded in the memory won’t update. You need to reload it, using reload() function in imp module.

>>> import imp
>>> imp.reload(test)
>>> test.SayHello("Deepak", "Python")
Hi Deepak! How are you?
Welcome to Python Tutorial by TutorialsPoint

Packages in Python

包是一个分层的目录结构,它定义了一个由模块、子包、子子包等等组成的单个 Python 应用程序环境。

A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules, subpackages and, sub-subpackages, and so on.

考虑 Phone 目录中提供的一个文件 Pots.py。该文件中有一行源代码 −

Consider a file Pots.py available in Phone directory. This file has following line of source code −

def Pots():
   print "I'm Pots Phone"

同样的方式,我们还有另外两个具有与上面相同名称的不同功能的文件 −

Similar way, we have another two files having different functions with the same name as above −

  1. Phone/Isdn.py file having function Isdn()

  2. Phone/G3.py file having function G3()

现在,在 Phone 目录中创建另一个文件 init .py −

Now, create one more file init.py in Phone directory −

  1. Phone/init.py

为了使导入 Phone 时所有函数可用,需要在 init .py 中放入显式 import 语句,如下所示 −

To make all of your functions available when you’ve imported Phone, you need to put explicit import statements in init.py as follows −

from Pots import Pots
from Isdn import Isdn
from G3 import G3

在将这些行添加到 init .py 后,在导入 Phone 包时,所有这些类都可用。

After you add these lines to init.py, you have all of these classes available when you import the Phone package.

# Now import your Phone Package.
import Phone

Phone.Pots()
Phone.Isdn()
Phone.G3()

执行上述代码后,将生成以下结果 −

When the above code is executed, it produces the following result −

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

在上面的示例中,我们采用了每个文件中单个函数的示例,但您可以在文件中保留多个函数。您还可以在这些文件中定义不同的 Python 类,然后可以从这些类中创建包。

In the above example, we have taken example of a single functions in each file, but you can keep multiple functions in your files. You can also define different Python classes in those files and then you can create your packages out of those classes.