Skip to content

模块和包

创建和导入模块

Python 模块

创建模块

python
# math_utils.py - 数学工具模块
"""数学工具模块,提供基本的数学运算函数"""

PI = 3.14159

def add(a, b):
    """返回两个数的和"""
    return a + b

def subtract(a, b):
    """返回两个数的差"""
    return a - b

def multiply(a, b):
    """返回两个数的积"""
    return a * b

def divide(a, b):
    """返回两个数的商"""
    if b == 0:
        raise ValueError("除数不能为零")
    return a / b

def power(base, exponent):
    """返回 base 的 exponent 次方"""
    return base ** exponent

# 模块级别的代码
if __name__ == "__main__":
    # 测试代码
    print("测试数学工具模块:")
    print(f"PI = {PI}")
    print(f"5 + 3 = {add(5, 3)}")
    print(f"10 - 4 = {subtract(10, 4)}")
    print(f"6 * 7 = {multiply(6, 7)}")
    print(f"15 / 3 = {divide(15, 3)}")
    print(f"2^8 = {power(2, 8)}")

导入模块

python
# main.py - 主程序文件
# 方式1:导入整个模块
import math_utils

result = math_utils.add(5, 3)
print(result)  # 8

# 方式2:导入特定函数
from math_utils import add, multiply

result = add(10, 5)
print(result)  # 15

# 方式3:导入所有函数(不推荐)
from math_utils import *

result = subtract(20, 8)
print(result)  # 12

# 方式4:使用别名
import math_utils as mu

result = mu.power(2, 10)
print(result)  # 1024

# 方式5:给函数起别名
from math_utils import add as addition

result = addition(7, 9)
print(result)  # 16

JavaScript 模块

创建模块

javascript
// mathUtils.js - 数学工具模块
/**
 * 数学工具模块,提供基本的数学运算函数
 */

export const PI = 3.14159;

export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

export function multiply(a, b) {
  return a * b;
}

export function divide(a, b) {
  if (b === 0) {
    throw new Error("除数不能为零");
  }
  return a / b;
}

export function power(base, exponent) {
  return base ** exponent;
}

// 默认导出
export default {
  add,
  subtract,
  multiply,
  divide,
  power,
  PI,
};

导入模块

javascript
// main.js - 主程序文件
// 方式1:导入整个模块
import * as mathUtils from "./mathUtils.js";

const result = mathUtils.add(5, 3);
console.log(result); // 8

// 方式2:导入特定函数
import { add, multiply } from "./mathUtils.js";

const result2 = add(10, 5);
console.log(result2); // 15

// 方式3:导入默认导出
import mathUtilsDefault from "./mathUtils.js";

const result3 = mathUtilsDefault.add(7, 9);
console.log(result3); // 16

// 方式4:使用别名
import * as mu from "./mathUtils.js";

const result4 = mu.power(2, 10);
console.log(result4); // 1024

// 方式5:给函数起别名
import { add as addition } from "./mathUtils.js";

const result5 = addition(7, 9);
console.log(result5); // 16

模块对比

特性PythonJavaScript
文件扩展名.py.js
导入语法import moduleimport { func } from './module.js'
默认导出__all__export default
命名空间module.function()module.function()
别名import module as aliasimport * as alias

创建和导入包

Python 包

创建包结构

my_package/
├── __init__.py
├── math_utils.py
├── string_utils.py
└── data_utils.py

包初始化文件

python
# my_package/__init__.py
"""我的工具包"""

from .math_utils import add, subtract, multiply, divide
from .string_utils import reverse_string, count_words
from .data_utils import load_data, save_data

__version__ = "1.0.0"
__author__ = "Your Name"

# 定义包的公共接口
__all__ = [
    'add', 'subtract', 'multiply', 'divide',
    'reverse_string', 'count_words',
    'load_data', 'save_data'
]

# 包级别的配置
PACKAGE_NAME = "MyPackage"

包中的模块

python
# my_package/math_utils.py
"""数学工具模块"""

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        raise ValueError("除数不能为零")
    return a / b
python
# my_package/string_utils.py
"""字符串工具模块"""

def reverse_string(text):
    """反转字符串"""
    return text[::-1]

def count_words(text):
    """计算单词数量"""
    return len(text.split())
python
# my_package/data_utils.py
"""数据处理工具模块"""

import json

def load_data(filename):
    """从文件加载数据"""
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        return {}

def save_data(data, filename):
    """保存数据到文件"""
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

使用包

python
# main.py - 使用包
# 方式1:导入整个包
import my_package

result = my_package.add(5, 3)
print(result)  # 8

# 方式2:从包中导入特定函数
from my_package import add, reverse_string

result = add(10, 5)
print(result)  # 15

text = reverse_string("Hello")
print(text)  # olleH

# 方式3:导入特定模块
from my_package import math_utils

result = math_utils.multiply(6, 7)
print(result)  # 42

# 方式4:使用别名
import my_package as mp

result = mp.count_words("Hello world")
print(result)  # 2

JavaScript 包

创建包结构

my-package/
├── package.json
├── index.js
├── math-utils.js
├── string-utils.js
└── data-utils.js

包配置文件

json
// my-package/package.json
{
  "name": "my-package",
  "version": "1.0.0",
  "description": "我的工具包",
  "main": "index.js",
  "type": "module",
  "exports": {
    ".": "./index.js",
    "./math": "./math-utils.js",
    "./string": "./string-utils.js",
    "./data": "./data-utils.js"
  },
  "keywords": ["utils", "tools"],
  "author": "Your Name",
  "license": "MIT"
}

包入口文件

javascript
// my-package/index.js
/**
 * 我的工具包入口文件
 */

export { add, subtract, multiply, divide } from "./math-utils.js";
export { reverseString, countWords } from "./string-utils.js";
export { loadData, saveData } from "./data-utils.js";

// 包信息
export const PACKAGE_NAME = "MyPackage";
export const VERSION = "1.0.0";

包中的模块

javascript
// my-package/math-utils.js
/**
 * 数学工具模块
 */

export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

export function multiply(a, b) {
  return a * b;
}

export function divide(a, b) {
  if (b === 0) {
    throw new Error("除数不能为零");
  }
  return a / b;
}
javascript
// my-package/string-utils.js
/**
 * 字符串工具模块
 */

export function reverseString(text) {
  return text.split("").reverse().join("");
}

export function countWords(text) {
  return text.split(/\s+/).filter((word) => word.length > 0).length;
}
javascript
// my-package/data-utils.js
/**
 * 数据处理工具模块
 */

import { promises as fs } from "fs";

export async function loadData(filename) {
  try {
    const data = await fs.readFile(filename, "utf-8");
    return JSON.parse(data);
  } catch (error) {
    if (error.code === "ENOENT") {
      return {};
    }
    throw error;
  }
}

export async function saveData(data, filename) {
  const jsonData = JSON.stringify(data, null, 2);
  await fs.writeFile(filename, jsonData, "utf-8");
}

使用包

javascript
// main.js - 使用包
// 方式1:导入整个包
import * as myPackage from "./my-package/index.js";

const result = myPackage.add(5, 3);
console.log(result); // 8

// 方式2:从包中导入特定函数
import { add, reverseString } from "./my-package/index.js";

const result2 = add(10, 5);
console.log(result2); // 15

const text = reverseString("Hello");
console.log(text); // olleH

// 方式3:导入特定模块
import { multiply } from "./my-package/math-utils.js";

const result3 = multiply(6, 7);
console.log(result3); // 42

// 方式4:使用别名
import * as mp from "./my-package/index.js";

const result4 = mp.countWords("Hello world");
console.log(result4); // 2

第三方包管理

Python pip

bash
# 安装包
pip install requests
pip install numpy pandas

# 安装特定版本
pip install requests==2.28.1

# 从 requirements.txt 安装
pip install -r requirements.txt

# 卸载包
pip uninstall requests

# 列出已安装的包
pip list

# 生成 requirements.txt
pip freeze > requirements.txt

JavaScript npm/yarn

bash
# 安装包
npm install axios
npm install lodash express

# 安装特定版本
npm install axios@1.3.4

# 从 package.json 安装
npm install

# 卸载包
npm uninstall axios

# 列出已安装的包
npm list

# 生成 package-lock.json
npm install

虚拟环境

Python 虚拟环境

bash
# 创建虚拟环境
python -m venv myenv

# 激活虚拟环境
# Windows
myenv\Scripts\activate

# macOS/Linux
source myenv/bin/activate

# 退出虚拟环境
deactivate

JavaScript 项目隔离

bash
# 初始化项目
npm init -y

# 安装依赖到 node_modules
npm install

# 使用 npx 运行本地安装的工具
npx eslint src/

练习

  1. 创建一个包含数学、字符串和数据处理功能的 Python 包

参考答案:

my_package/
├── __init__.py
├── math_utils.py
├── string_utils.py
└── data_utils.py

math_utils.py:

python
def add(a, b):
    return a + b

string_utils.py:

python
def reverse_string(s):
    return s[::-1]

data_utils.py:

python
import json
def load_json(filename):
    with open(filename, 'r', encoding='utf-8') as f:
        return json.load(f)

__init__.py:

python
from .math_utils import add
from .string_utils import reverse_string
from .data_utils import load_json
  1. 创建一个 JavaScript 包,提供类似的工具函数

参考答案:

my-package/
├── index.js
├── math-utils.js
├── string-utils.js
└── data-utils.js

math_utils.js:

javascript
export function add(a, b) {
  return a + b;
}

string-utils.js:

javascript
export function reverseString(s) {
  return s.split("").reverse().join("");
}

data-utils.js:

javascript
import { promises as fs } from "fs";
export async function loadJson(filename) {
  const data = await fs.readFile(filename, "utf-8");
  return JSON.parse(data);
}

index.js:

javascript
export * from "./math-utils.js";
export * from "./string-utils.js";
export * from "./data-utils.js";
  1. 练习不同的模块导入方式

参考答案:

python
# Python
from my_package import add
from my_package.string_utils import reverse_string
import my_package.data_utils as du
javascript
// JavaScript
import { add } from "./my-package/math-utils.js";
import * as strUtils from "./my-package/string-utils.js";
import { loadJson } from "./my-package/data-utils.js";
  1. 使用第三方包(如 requests 或 axios)进行 HTTP 请求

参考答案:

python
# Python
import requests
response = requests.get("https://api.github.com")
print(response.status_code)
javascript
// JavaScript (Node.js)
const axios = require("axios");
axios.get("https://api.github.com").then((res) => {
  console.log(res.status);
});
  1. 设置虚拟环境并管理依赖

参考答案:

bash
# Python
python -m venv venv
source venv/bin/activate  # Windows 用 venv\Scripts\activate
pip install requests

# JavaScript
npm init -y
npm install axios

下一步

现在你已经了解了模块和包的使用,接下来我们将学习文件操作。