python模块的导入方式

不同的导入方式

导入整个模块

import os
import sys
import json

注意使用时要带上模块名:

import math

# 使用时需要模块名前缀
result = math.sqrt(16)      # 4.0
print(math.pi)              # 3.141592653589793

导入特定函数/类

from math import sqrt, pi, sin, cos
from datetime import datetime, date, timedelta
from collections import Counter, defaultdict

导入所有(不推荐)

from math import *  # 导入math模块的所有内容
# 现在可以直接使用
print(sqrt(9))      # 3.0
print(pi)           # 3.141592653589793
print(sin(0))       # 0.0

别名导入

# 给模块起别名
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# 给函数/类起别名
from datetime import datetime as dt
from math import sqrt as square_root

# 使用别名
now = dt.now()
result = square_root(25)

不同导入方式对比

特性 import module from module import name from module import *
命名空间​ 干净,需前缀 可能污染命名空间 严重污染命名空间
可读性​ 明确来源 简洁但来源不明 来源完全不明确
内存​ 导入整个模块 只导入需要的 导入所有(最占内存)
冲突风险​

简单决策指南

  • 大多数情况:用 import module,特别是标准库
  • 频繁使用的函数:用 from module import specific_name
  • 大库(numpy, pandas):用 import module as alias
  • 永远不要用:from module import *(除了在 REPL 中测试)
posted @ 2026-04-29 16:23  MKYC  阅读(3)  评论(0)    收藏  举报