python导入模块
Python import statement is used to import modules that we want to use in our program. Python modules are python scripts containing utility functions, types, classes etc. There are many modules that we use regularly in python programs such as sys, os, collections etc.
Python import语句用于导入要在程序中使用的模块。 Python模块是包含实用程序功能,类型,类等的python脚本。我们在python程序中定期使用许多模块,例如sys , os , collections等。
Python导入 (Python import)
If we want to import python built-in modules or any third party module installed using a package manager such as PIP, then we can very easily import and use them in our program.
如果我们要导入python内置模块或使用软件包管理器(如PIP)安装的任何第三方模块,则可以非常轻松地在程序中导入和使用它们。
import collections
import sys
Python looks for modules and packages into sys.path
property. This path always contains the current directory from where the script is executed, so any module in the current directory can be imported as is.
Python在sys.path
属性中查找模块和包。 该路径始终包含执行脚本的当前目录,因此可以直接导入当前目录中的任何模块。
Python imports are case sensitive, so import sys
and import Sys
are looking for different modules to import.
Python导入区分大小写,因此import sys
和import Sys
正在寻找要导入的不同模块。
Python looks for a module into the built-in modules first. If not found, then it searches for modules in the current directory. So if we have math.py
file in the same directory as our main script, then it will be loaded when import math
is called if ‘math’ module is not in the built-in modules. You can get a list of built-in modules using sys.builtin_module_names
. Below image shows the built-in modules in my python installation.
Python首先在内置模块中寻找模块。 如果找不到,它将在当前目录中搜索模块。 因此,如果我们的math.py
文件与主脚本位于同一目录中,那么如果内置模块中没有'math'模块,则在调用import math
时将加载该文件。 您可以使用sys.builtin_module_names
获得内置模块的列表。 下图显示了我的python安装中的内置模块。
Python从模块导入类/函数 (Python import class/functions from module)
We can import specific classes from module too. This way we can import specific parts of a module and use it. This also helps in writing fluent code. We can achieve this using from keyword with the import statement.
我们也可以从模块导入特定的类。 这样,我们可以导入模块的特定部分并使用它。 这也有助于编写流畅的代码。 我们可以在导入语句中使用from关键字来实现。
from collections import namedtuple
from os import path
Python导入用户定义的模块 (Python import user-defined module)
When we create a python script, we can import it into another python script using its name. Let’s say we have following directory structure with multiple python scripts.
创建python脚本时,可以使用其名称将其导入另一个python脚本中。 假设我们具有以下带有多个python脚本的目录结构。
We have following functions defined in utils.py
file.
我们在utils.py
文件中定义了以下函数。
def add(i, j):
return int(i) + int(j)
def uppercase(s):
return str(s).upper()
We can import it into python_import_examples.py
and use its functions.
我们可以将其导入python_import_examples.py
并使用其功能。
import utils
print(utils.add(10,10))
print(utils.uppercase('java'))
Output:
输出:
20
JAVA
Python导入为 (Python import as)
We can define our own name for the imported module using import as
statement.
我们可以使用import as
语句为导入的模块定义自己的名称。
# python import as
import utils as u
print(u.add(10,10))
print(u.uppercase('java'))
The result will be the same as the earlier program.
结果将与以前的程序相同。
从另一个目录导入Python (Python import from another directory)
If the python script we are importing is in the same directory, then we can import is easily just like built-in modules. However, if the python script is present in another directory, then we can use importlib
library to import them as a module.
如果我们要导入的python脚本位于同一目录中,那么我们可以像内置模块一样轻松地导入。 但是,如果python脚本位于另一个目录中,那么我们可以使用importlib
库将其作为模块导入。
Let’s say our strutils.py
has following functions:
假设我们的strutils.py
具有以下功能:
def uppercase(s):
return str(s).upper()
def lowercase(s):
return str(s).lower()
Now let’s see how to use importlib to import this python script into our example.
现在,让我们看看如何使用importlib将这个python脚本导入到我们的示例中。
# Refer: https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
# Refer: https://stackoverflow.com/questions/4383571/importing-files-from-different-folder
import importlib, importlib.util
def module_from_file(module_name, file_path):
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
strutils = module_from_file("strutils", "../mymodule/strutils.py")
print(strutils.uppercase('java'))
print(strutils.lowercase('DATA'))
Python从另一个文件导入类 (Python import class from another file)
We can import scripts and use the classes defined in them using importlib too. Let’s say we have classes Person
and Student
defined in myclasses.py
file.
我们也可以使用importlib导入脚本并使用其中定义的类。 假设我们在myclasses.py
文件中定义了Person
和Student
类。
class Person:
name = ""
def __init__(self, personName):
self.name = personName
def showName(self):
print(self.name)
class Student(Person):
id = 0
def __init__(self, studentName, studentId):
Person.__init__(self, studentName)
self.id = studentId
def getId(self):
return self.id
Here is the example code where I am using the earlier defined function to import this script and use its classes.
这是示例代码,其中我使用较早定义的函数来导入此脚本并使用其类。
#python import class from another file
mc = module_from_file("myclasses", "../mymodule/myclasses.py")
p = mc.Person('Pankaj')
p.showName()
s = mc.Student('David',25)
s.showName()
print(s.getId())
Notice that we can keep any name for the module we are importing, it’s similar to using import as
statement.
注意,我们可以为要导入的模块保留任何名称,这类似于使用import as
语句。
There is another way to import scripts from another directory using the sys
module.
还有一种使用sys
模块从另一个目录导入脚本的方法。
import sys
sys.path.append("../mymodule/")
from myclasses import Person as PC
p = PC('Meghna')
p.showName()
This is useful when we want to import only specific classes and functions from the imported file. Also, using this code is much easier to understand.
当我们只想从导入的文件中导入特定的类和函数时,这很有用。 而且,使用此代码更容易理解。
摘要 (Summary)
Python import statement allows us to import modules, python scripts, specific classes and functions from modules. It’s very easy to use and since most of the times we work on built-in modules or modules installed using PIP, we don’t need to write logic to load scripts from another directory.
Python import语句使我们可以从模块中导入模块,python脚本,特定的类和函数。 它非常易于使用,并且由于大多数时候我们都在处理内置模块或使用PIP安装的模块,因此我们无需编写逻辑即可从另一个目录加载脚本。
Reference: Official Documentation
参考: 官方文档
python导入模块