python 中from import 有哪些方式导入

在 Python 中,from ... import ... 语句有多种变体,用于从模块中导入特定的对象、函数、类或子模块。以下是所有常见的导入方式及示例:


1. 基本导入方式

(1) 导入整个模块

import module_name

示例:

import math
print(math.sqrt(16))  # 4.0

(2) 从模块导入特定对象

from module_name import name1, name2

示例:

from math import sqrt, pi
print(sqrt(16))  # 4.0
print(pi)        # 3.141592653589793

(3) 导入所有对象(不推荐,易造成命名冲突)

from module_name import *

示例:

from math import *
print(sqrt(16))  # 4.0
print(pi)        # 3.141592653589793

2. 别名导入(as)

(4) 给模块起别名

import module_name as alias

示例:

import numpy as np
print(np.array([1, 2, 3]))  # [1 2 3]

(5) 给导入的对象起别名

from module_name import name as alias

示例:

from math import sqrt as square_root
print(square_root(16))  # 4.0

3. 相对导入(用于包内部)

(6) 从当前包的子模块导入

from .submodule import name

示例:
假设目录结构:

 
my_package/
    __init__.py
    utils.py
    main.py

在 main.py 中导入 utils.py 的函数:

from .utils import my_function

(7) 从父包的子模块导入

from ..sibling_module import name

示例:

my_project/
    package1/
        __init__.py
        module1.py
    package2/
        __init__.py
        module2.py

在 package2/module2.py 中导入 package1/module1.py

from ..package1.module1 import some_function

4. 动态导入(运行时导入)

(8) 使用 importlib 动态导入

import importlib
module = importlib.import_module("module_name")

示例:

module = importlib.import_module("math")
print(module.sqrt(16))  # 4.0

(9) 动态导入并获取属性

from importlib import import_module
module = import_module("module_name")
attr = getattr(module, "function_name")

示例:

math_module = import_module("math")
sqrt_func = getattr(math_module, "sqrt")
print(sqrt_func(16))  # 4.0

5. 条件导入

(10) 根据条件导入不同模块

if condition:
    from module1 import name
else:
    from module2 import name

示例:

import sys

if sys.platform == "linux":
    from linux_utils import get_system_info
else:
    from windows_utils import get_system_info

6. 延迟导入(Lazy Import)

(11) 在函数内部导入(减少启动时间)

def my_function():
    from heavy_module import expensive_operation
    return expensive_operation()

示例:

def calculate():
    from numpy import array  # 只有调用 calculate() 时才导入
    return array([1, 2, 3])

总结

导入方式语法适用场景
基本导入 import module 导入整个模块
导入特定对象 from module import name 只导入需要的部分
通配符导入 from module import * 快速导入所有(不推荐)
别名导入 import module as alias 避免命名冲突
相对导入 from .submodule import name 包内部模块导入
动态导入 importlib.import_module() 运行时决定导入内容
条件导入 if ...: from ... import ... 根据环境选择导入
延迟导入 在函数内部 import 优化启动时间

你可以根据需求选择合适的导入方式!

posted @ 2025-06-24 19:46  郭慕荣  阅读(63)  评论(0)    收藏  举报