一,简介
Adapter Augustone Zhang
Updated: August 8, 2019
Explore this Article Using the from-import instruction Using the import instruction Ask a Question Related Articles
Python's syntax allows for code to be significantly shortened by using something called modules. Similar to header files in C++, modules are a storage place for the definitions of functions. They are separated into common uses, such as the time module, which provides functions for time related uses.
#类似于C语言的头文件,python可以通过引用已有的模块(他人编写的可复用的成熟的有特定功能的代码集)来减少编程人员的工作量
Using the from-import instruction
from 模块 import 函数
The from-import instruction imports functions from a module and lets you use them like functions from the core Python. You don't see that the functions belong to the module.
-
-
To import a specific function from a specific module, write:#从模块里引入一个特定的函数,亦即并非模块中所有的函数变量都拿过来,只拿一部分。这种方式使用时无需前缀
from [module] import [function]
- For example, to import the
randint
function from therandom
module and print a random number using that function, you would write:from random import randint print(randint(0, 5))
- For example, to import the
-
Separate multiple functions from the same module with commas (,). The structure looks like this:#同时引入模块的多个函数,以逗号分割函数名
from [module] import [function], [otherFunction], [anotherFunction], ...
- For example, to import the
randint
andrandom
functions from therandom
module and print random numbers using these functions, you would write:from random import randint, random print(randint(0, 5)) print(random())
- For example, to import the
-
Import entire modules using a
*
instead of a function name. The structure looks like this:#一次性同时引入一个模块的所有内容。这样做虽然引入时方便到引入很多问题。因为这个时候不需要前缀,失去了层次性,结果导致潜在的命名冲突from [module] import *
- For example, to import the entire
random
module and then print a random number with itsrandint
function, you would write:from random import * print(randint(0, 5))
- For example, to import the entire
-
Import multiple modules by writing multiple from-import instructions. #无他,一种写法而已。而且为了直观,最好分行写You should start a new line for each instruction to keep the code readable, although separating them with a
;
also works.- For example, to import the
randint
function from therandom
module and thesqrt
function from themath
module and then print a result from both functions, you would write: -
from random import randint from math import sqrt # Would also work, but hard to read: # from random import randint; from math import sqrt print(randint(0, 5)) print(sqrt(25))
- For example, to import the
Using the import instruction#直接import
The import instruction imports functions from a module and leaves it visible that the functions are from that module. When using a function imported with the import instruction, you have to write the module name and a dot (.) before it.
The import instruction doesn't allow to import a single function from a module without also importing all others.
-
-
To import a module, write with the following structure:import [module]
- For example, to import the
random
module and then print a random number with itsrandint
function:import random print(random.randint(0, 5))
#这个时候导入的不是具体的函数,而是导入模块。此时引用需要带模块名
- For example, to import the
-
Separate multiple modules with a comma (,). The structure is:#引入多个模块
import [module], [otherModule], [anotherModule], ...
- For example, to import the
random
andmath
modules and then print the results of therandint
andsqrt
functions that are included in these modules, you would write:import random, math print(random.randint(0, 5)) print(math.sqrt(25))
- For example, to import the
二,较为全面的介绍
Introduction
The Python programming language comes with a variety of built-in functions. Among these are several common functions, including:#Python有一些内置函数
print()
which prints expressions outabs()
which returns the absolute value of a numberint()
which converts another data type to an integerlen()
which returns the length of a sequence or collection
These built-in functions, however, are limited, and we can make use of modules to make more sophisticated programs.#但是这些内置函数还不够多,我们可以请module来帮助
Modules are Python .py
files that consist of Python code#module也是.py结尾的python代码. Any Python file can be referenced as a module#不神秘,事实上任何python代码文件都可以看做模块. A Python file called hello.py
has the module name of hello
that can be imported into other Python files or used on the Python command line interpreter. You can learn about creating your own modules by reading How To Write Modules in Python 3.
Modules can define functions, classes, and variables that you can reference in other Python#重要!模块可以定义函数、类、变量,因此实际上模块不仅包括函数! .py
files or via the Python command line interpreter.
In Python, modules are accessed by using the import
statement. When you do this, you execute the code of the module, keeping the scopes of the definitions so that your current file(s) can make use of these.
When Python imports a module called hello
for example, the interpreter will first search for a built-in module called hello
. If a built-in module is not found, the Python interpreter will then search for a file named hello.py
in #当前目录,然后 in a list of directories that it receives from the sys.path
variable.#这是搜索顺序!
不仅如此,sys.path路径还可以临时更改。使用sys.path.append、sys.path.insert
This tutorial will walk you through checking for and installing modules, importing modules, and aliasing modules.
Checking For and Installing Modules
There are a number of modules that are built into the Python Standard Library, which contains many modules that provide access to system functionality or provide standardized solutions. The Python Standard Library is part of every Python installation.
To check that these Python modules are ready to go, enter into your local Python 3 programming environment or server-based programming environment and start the Python interpreter in your command line like so:
- python
From within the interpreter you can run the import
statement to make sure that the given module is ready to be called, as in:
- import math#内置模块
Since math
is a built-in module, your interpreter should complete the task with no feedback, returning to the prompt. This means you don’t need to do anything to start using the math
module.
Let’s run the import
statement with a module that you may not have installed, like the 2D plotting library matplotlib
:
- import matplotlib#第三方模块
If matplotlib
is not installed, you’ll receive an error like this:
ImportError: No module named 'matplotlib'
You can deactivate the Python interpreter with CTRL + D
and then install matplotlib
with pip
.
Next, we can use pip
to install the matplotlib
module:
- pip install matplotlib#安装第三方模块
Once it is installed, you can import matplotlib
in the Python interpreter using import matplotlib
, and it will complete without error.
Importing Modules
To make use of the functions in a module, you’ll need to import the module with an import
statement.
An import
statement is made up of the import
keyword along with the name of the module.
In a Python file, this will be declared at the top of the code, under any shebang lines or general comments.
So, in the Python program file my_rand_int.py
we would import the random
module to generate random numbers in this manner:
import random
When we import a module, we are making it available to us in our current program as a separate namespace. This means that we will have to refer to the function in dot notation, as in [module].[function]
.
In practice, with the example of the random
module, this may look like a function such as:
random.randint()
which calls the function to return a random integer, orrandom.randrange()
which calls the function to return a random element from a specified range.
Let’s create a for
loop to show how we will call a function of the random
module within our my_rand_int.py
program:
import random#import 模块 方式导入,需要使用前缀才能使用相应函数
for i in range(10):
print(random.randint(1, 25))
This small program first imports the random
module on the first line, then moves into a for
loop which will be working with 10 elements. Within the loop, the program will print a random integer within the range of 1 through 25 (inclusive). The integers 1
and 25
are passed to random.randint()
as its parameters.
When we run the program with python my_rand_int.py
, we’ll receive 10 random integers as output. Because these are random you’ll likely get different integers each time you run the program, but they’ll look something like this:
6
9
1
14
3
22
10
1
15
9
The integers should never go below 1 or above 25.
If you would like to use functions from more than one module, you can do so by adding multiple import
statements:
import random
import math
You may see programs that import multiple modules with commas separating them — as in import random, math
— but this is not consistent with the PEP 8 Style Guide.
To make use of our additional module, we can add the constant pi
from math
to our program, and decrease the number of random integers printed out:
import random
import math
for i in range(5):
print(random.randint(1, 25))
print(math.pi)
Now, when we run our program, we’ll receive output that looks like this, with an approximation of pi as our last line of output:
18
10
7
13
10
3.141592653589793
The import
statement allows you to import one or more modules into your Python program, letting you make use of the definitions constructed in those modules.
Using from
... import
To refer to items from a module within your program’s namespace, you can use the from
... import
statement. When you import modules this way, you can refer to the functions by name rather than through dot notation#无需前缀了
In this construction, you can specify which definitions to reference directly.
In other programs, you may see the import
statement take in references to everything defined within the module by using an asterisk (*
) as a wildcard, but this is discouraged by PEP 8.#不鼓励使用*
Let’s first look at importing one specific function, randint()
from the random
module:
from random import randint
Here, we first call the from
keyword, then random
for the module. Next, we use the import
keyword and call the specific function we would like to use.
Now, when we implement this function within our program, we will no longer write the function in dot notation as random.randint()
but instead will just write randint()
:
from random import randint
for i in range(10):
print(randint(1, 25))
When you run the program, you’ll receive output similar to what we received earlier.
Using the from
... import
construction allows us to reference the defined elements of a module within our program’s namespace, letting us avoid dot notation.
Aliasing Modules#别名或缩略名
It is possible to modify the names of modules and their functions within Python by using the as
keyword.
You may want to change a name because you have already used the same name for something else in your program, another module you have imported also uses that name, or you may want to abbreviate a longer name that you are using a lot.
The construction of this statement looks like this:
import [module] as [another_name]
Let’s modify the name of the math
module in our my_math.py
program file. We’ll change the module name of math
to m
in order to abbreviate it. Our modified program will look like this:
import math as m
print(m.pi)
print(m.e)
Within the program, we now refer to the pi
constant as m.pi
rather than math.pi
.
For some modules, it is commonplace to use aliases. The matplotlib.pyplot
module’s official documentation calls for use of plt
as an alias:
import matplotlib.pyplot as plt
This allows programmers to append the shorter word plt
to any of the functions available within the module, as in plt.show()
. You can see this alias import statement in use within our “How to Plot Data in Python 3 Using matplotlib
tutorial.”
Conclusion
When we import modules we’re able to call functions that are not built into Python. Some modules are installed as part of Python, and some we will install through pip
.
Making use of modules allows us to make our programs more robust and powerful as we’re leveraging existing code. We can also create our own modules for ourselves and for other programmers to use in future programs.
三,自己写的模块
A Beginner's Python Tutorial/Importing Modules
Last lesson we covered the killer topic of Classes. As you can remember, classes are neat combinations of variables and functions in a nice, neat package. Programming lingo calls this feature encapsulation, but regardless of what it is called, it's a really cool feature for keeping things together so the code can be used in many instances in lots of places. Of course, you've got to ask, "how do I get my classes to many places, in many programs?". The answer is to put them into a module, to be imported into other programs.
Module? What's a Module?
A module is a Python file that (generally) has only definitions of variables, functions, and classes. For example, a module might look like this:#定义了变量、函数、类的py文件
- Code Example 1 - moduletest.py#命名一个py,该py将被看做模块儿
### EXAMPLE PYTHON MODULE
# Define some variables:
numberone = 1
ageofqueen = 78
# define some functions
def printhello():
print "hello"
def timesfour(input):
print input * 4
# define a class
class Piano:
def __init__(self):
self.type = input("What type of piano? ")
self.height = input("What height (in feet)? ")
self.price = input("How much did it cost? ")
self.age = input("How old is it (in years)? ")
def printdetails(self):
print "This piano is a/an " + self.height + " foot",
print self.type, "piano, " + self.age, "years old and costing
" + self.price + " dollars."
As you see, a module looks pretty much like your normal Python program.
So what do we do with a module? We import bits of it (or all of it) into other programs.#在其他应用程序中导入部分扩全部
To import all the variables, functions and classes from moduletest.py into another program you are writing, we use the import operator. For example, to import moduletest.py into your main program, you would have this:
- Code Example 2 - mainprogram.py#主程序
### mainprogam.py
### IMPORTS ANOTHER MODULE
import moduletest#引入模块
This assumes that the module is in the same directory as mainprogram.py#解释器将搜索当前目录
, or is a default module that comes with python#首先搜索内置模块. You leave out the '.py' at the end of the file - it is ignored. You normally put all import statements at the beginning of the python file, but technically they can be anywhere. In order to use the items of the module in your main program, you use the following:
- Code Example 3 - mainprogram.py continued
### USING AN IMPORTED MODULE
# Use the form modulename.itemname
# Examples:
print moduletest.ageofqueen#这里使用的是python2,没关系。这里引用的是变量
cfcpiano = moduletest.Piano()#引用的是类
cfcpiano.printdetails()#类方法
#事实上也可以引用函数
As you see, the modules that you import act very much like the classes we looked at last lesson - anything inside them must be preceded with modulename for it to work.
More About Modules
Wish you could get rid of the modulename part that you have to put before every item you use from a module? No? Never? Well, I'll teach it to you anyway.
One way to avoid this hassle is to import only the wanted objects from the module#可以仅仅引入你需要的对象. To do this, you use the from operator. You use it in the form of from modulename import itemname. Here is an example:
- Code Example 4 - importing individual objects
### IMPORT ITEMS DIRECTLY INTO YOUR PROGRAM
# import them
from moduletest import ageofqueen
from moduletest import printhello
# now try using them
print ageofqueen
printhello()#无前缀引用函数
What is the point of this? Well, maybe you could use it to make your code a little more readable. If we get into heaps of modules inside modules, it could also remove that extra layer of crypticness.
If you wanted to, you could import everything from a module in this way by using from modulename import *. Of course, this can be troublesome if there are objects in your program with the same name as some items in the module. With large modules, this can easily happen, and can cause many a headache. A better way to do this would be to import a module in the normal way (without the from operator) and then assign items to a local name:
- Code Example 5 - mainprogram.py continued
### ASSIGNING ITEMS TO A LOCAL NAME
# Assigning to a local name
timesfour = moduletest.timesfour
# Using the local name
print timesfour(565)
This way, you can remove some crypticness, AND have all of the items from a certain module.
四,python的包
mycompany
├─ web
│ ├─ __init__.py
│ ├─ utils.py
│ └─ www.py
├─ __init__.py
├─ abc.py
└─ xyz.py
Python中的包的实例
包是一个分层次的文件目录结构,它定义了一个由模块及子包,和子包下的子包等组成的 Python 的应用环境。
简单来说,包就是文件夹,但该文件夹下必须存在 __init__.py 文件, 该文件的内容可以为空。__init__.py 用于标识当前文件夹是一个包。
考虑一个在 package_augustone 目录下的 1.py、2.py、__init__.py 文件,test.py 为测试调用包的代码,目录结构如下:
test.py
package_augustone
|-- __init__.py
|-- test1.py
|-- test2.py
from package_augustone.test1 import function_in_test1
from package_augustone.test2 import function(or 变量、类) in test2
#此例说明两点,一、包中模块的引入使用包.模块方式!二、包为目录,而非py文件,且相应目录下必须有__iniy__.py
五、增强内容
' demo local execution and call as a module '
__author__ = 'Augustone Zhang'
def addThreeNumber(x, y, z):
return x + y + z
def aTimesB(a, b):
return a / b
def strTimes3(m):
m = str(m)
return m * 3
print(__name__) #如果作为主程序执行则打印出__main__,被调用则打印模块名
if __name__ == '__main__':
print('程序自身在运行')#如果作为主程序执行则执行这个if
else:
print('我来自另一模块')#如果被调用执行则执行这个else