常用命令
| 命令 |
功能 |
示例 |
/help |
查看帮助菜单和所有可用命令 |
/help |
/clear |
清空当前对话历史 |
/clear |
/model |
切换 AI 模型 |
/model claude-haiku-4-5-20251001 |
/permissions |
管理文件操作权限 |
/permissions |
/exit |
退出 Claude Code |
/exit |
代码生成示例
示例 1:生成带注释的函数
输入指令:
帮我生成一个 Python 函数,实现快速排序算法,要求包含详细注释和类型提示
AI 输出示例:
def quick_sort(arr: list[int]) -> list[int]:
"""
快速排序算法实现
参数:
arr: 待排序的整数列表
返回:
排序后的列表
时间复杂度: O(n log n) 平均情况
空间复杂度: O(log n) 递归栈空间
"""
if len(arr) <= 1:
return arr
# 选择基准值(这里选择中间元素)
pivot = arr[len(arr) // 2]
# 分区:小于、等于、大于基准值的元素
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
# 递归排序并合并
return quick_sort(left) + middle + quick_sort(right)
# 测试
if __name__ == "__main__":
test_arr = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = quick_sort(test_arr)
print(f"原数组: {test_arr}")
print(f"排序后: {sorted_arr}")
示例 2:代码重构
输入指令:
重构以下代码,使其更符合 PEP 8 规范并提高可读性:
def calc(a,b,op):
if op=='+':
return a+b
elif op=='-':
return a-b
elif op=='*':
return a*b
elif op=='/':
return a/b
AI 输出示例:
from typing import Union
def calculate(
operand_a: Union[int, float],
operand_b: Union[int, float],
operator: str
) -> Union[int, float]:
"""
执行基本算术运算
参数:
operand_a: 第一个操作数
operand_b: 第二个操作数
operator: 运算符 ('+', '-', '*', '/')
返回:
运算结果
异常:
ValueError: 当运算符无效时
ZeroDivisionError: 当除数为 0 时
"""
operations = {
'+': lambda a, b: a + b,
'-': lambda a, b: a - b,
'*': lambda a, b: a * b,
'/': lambda a, b: a / b,
}
if operator not in operations:
raise ValueError(f"不支持的运算符: {operator}")
if operator == '/' and operand_b == 0:
raise ZeroDivisionError("除数不能为零")
return operations[operator](operand_a, operand_b)
# 使用示例
try:
result = calculate(10, 5, '+')
print(f"结果: {result}")
except (ValueError, ZeroDivisionError) as e:
print(f"错误: {e}")
示例 3:生成单元测试
输入指令:
为上面的 calculate 函数生成完整的 pytest 单元测试
AI 输出示例:
import pytest
from your_module import calculate
class TestCalculate:
"""calculate 函数的单元测试"""
def test_addition(self):
"""测试加法运算"""
assert calculate(10, 5, '+') == 15
assert calculate(-3, 7, '+') == 4
assert calculate(0, 0, '+') == 0
def test_subtraction(self):
"""测试减法运算"""
assert calculate(10, 5, '-') == 5
assert calculate(5, 10, '-') == -5
assert calculate(0, 5, '-') == -5
def test_multiplication(self):
"""测试乘法运算"""
assert calculate(10, 5, '*') == 50
assert calculate(-3, 4, '*') == -12
assert calculate(0, 100, '*') == 0
def test_division(self):
"""测试除法运算"""
assert calculate(10, 5, '/') == 2.0
assert calculate(7, 2, '/') == 3.5
assert calculate(0, 5, '/') == 0.0
def test_division_by_zero(self):
"""测试除以零的异常处理"""
with pytest.raises(ZeroDivisionError, match="除数不能为零"):
calculate(10, 0, '/')
def test_invalid_operator(self):
"""测试无效运算符的异常处理"""
with pytest.raises(ValueError, match="不支持的运算符"):
calculate(10, 5, '%')
with pytest.raises(ValueError, match="不支持的运算符"):
calculate(10, 5, 'invalid')
def test_float_operations(self):
"""测试浮点数运算"""
assert calculate(10.5, 2.5, '+') == 13.0
assert calculate(10.5, 2.5, '*') == 26.25