Python 入门简明教程
1. 1. 与 Python 的第一次亲密接触-写给初学者 2. 2. Python 语法关键字 3. 3. Python 的注释和语法 4. 4. Python 基本数据类型 5. 5. Python 输入输出 6. 6. Python 运算符 7. 7. Python 变量 8. 8. Python 命名空间和变量生存范围 9. 9. Python 逻辑判断 10. 10. Python For 循环语法 11. 11. Python While 循环语法 12. 12. Python 循环语法中 break 与 continue的使用 13. 14. Python 三目运算符 14. 15. Python 循环语法中 pass 语句的使用 15. 16. Python 循环语法示例 16. 17. Python 函数 17. 18. Python main 函数 18. 19. Python print 函数 19. 20. Python print format 输出格式化 20. 21. Python print 输出到文件 21. 22. Python 输入 22. 23. Python import 导入模块 23. 25. Python 中递归的使用 24. 26. Python 匿名函数 25. 27. Python lambda 26. 28. Python PIP 包管理机制 27. 29. Python 命令行参数 28. 30. Python Numbers 包 29. 31. Python 随机数 30. 32. Python String 转 int 31. 34. Python 自定义异常 Exception 32. 35. Python 继承 33. 36. Python 父类 34. 38. Python 操作符重载 35. 39. Python __str__ and __repr__

23. Python import 导入模块

Python import语句用于导入要在程序中使用的模块。Python模块是包含实用函数、类型、类等的Python脚本系统,操作系统,收藏等。

Python导入

如果我们想要导入python内置模块或任何使用包管理器安装的第三方模块,比如皮普,这样我们就可以很容易地导入并在程序中使用它们。


import collections
import sys

Python在中查找模块和包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导入区分大小写,因此import sys and import Sys are looking for different modules to import.

Python首先在内置模块中查找模块。如果未找到,则在当前目录中搜索模块。所以如果我们有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从模块导入类/函数

我们也可以从模块中导入特定的类。这样我们就可以导入模块的特定部分并使用它。这也有助于编写流畅的代码。我们可以使用from关键字和import语句来实现这一点。


from collections import namedtuple
from os import path

Python导入自定义模块

创建python脚本时,可以使用其名称将其导入到另一个python脚本中。假设我们有以下目录结构和多个python脚本。

我们在中定义了以下函数utils.py file.


def add(i, j):
    return int(i) + int(j)

def uppercase(s):
    return str(s).upper()

我们可以把它导入python_import_examples.py and use its functions.


import utils

print(utils.add(10,10))
print(utils.uppercase("java"))

输出:


20
JAVA

Python导入为

我们可以使用import as statement.


# python import as
import utils as u

print(u.add(10,10))
print(u.uppercase("java"))

结果将与之前的程序相同。

从其他目录导入Python

如果我们要导入的python脚本在同一个目录中,那么我们可以很容易地导入,就像内置模块一样。但是,如果python脚本存在于另一个目录中,那么我们可以使用importlib library to import them as a module.

假设我们strutils.py has following functions:


def uppercase(s):
    return str(s).upper()

def lowercase(s):
    return str(s).lower()

现在让我们看看如何使用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从另一个文件导入类

我们也可以使用importlib导入脚本并使用其中定义的类。假设我们有课Person and Student defined in myclasses.py file.


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

下面是我使用前面定义的函数导入脚本并使用其类的示例代码。


#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())

请注意,我们可以为要导入的模块保留任何名称,它与使用import as statement.

还有另一种方法可以使用sys module.


import sys
sys.path.append("../mymodule/")
from myclasses import Person as PC
p = PC("Meghna")
p.showName()

当我们只想从导入的文件中导入特定的类和函数时,这很有用。此外,使用此代码更容易理解。

摘要

Python import语句允许我们从模块中导入模块、Python脚本、特定的类和函数。它非常容易使用,而且由于大多数时候我们使用内置模块或使用PIP安装的模块,我们不需要编写逻辑来从另一个目录加载脚本。

您可以从我们的GitHub存储库.

参考文献:官方文件