软件开发新手入门五大核心技能之基础编程能力(三)

简介: 教程来源 http://yyvgt.cn/ 本章深入讲解函数与模块化编程:涵盖Python/Java/JS中函数定义、参数传递(默认/关键字/可变参数)、作用域与闭包、递归原理及优化技巧(汉诺塔、备忘录、尾递归),强调代码复用与健壮性设计。

第四章 函数与模块化 —— 代码复用的艺术

4.1 函数的定义与调用
函数的基本结构

# Python函数完整定义
def calculate_bmi(weight_kg, height_m):
    """
    计算身体质量指数(BMI)

    参数:
        weight_kg: 体重(千克)
        height_m: 身高(米)

    返回:
        BMI值(浮点数)
    """
    if height_m <= 0:
        raise ValueError("身高必须为正数")
    bmi = weight_kg / (height_m ** 2)
    return bmi

# 调用函数
bmi = calculate_bmi(70, 1.75)
print(f"BMI: {bmi:.2f}")

# 参数传递的深度理解
# Python中参数传递是"对象引用传递"
def modify_list(lst):
    lst.append(4)      # 修改传入的列表对象
    lst = [1, 2, 3]    # 重新绑定,不影响外部
    print(f"函数内部: {lst}")

my_list = [1, 2, 3]
modify_list(my_list)
print(f"函数外部: {my_list}")  # [1,2,3,4] - append生效
// Java方法定义
public class Calculator {

    // 基本方法
    public static int add(int a, int b) {
        return a + b;
    }

    // 重载(Overloading):相同方法名,不同参数
    public static int add(int a, int b, int c) {
        return a + b + c;
    }

    public static double add(double a, double b) {
        return a + b;
    }

    // 可变参数
    public static int sum(int... numbers) {
        int total = 0;
        for (int num : numbers) {
            total += num;
        }
        return total;
    }

    // 递归方法:阶乘
    public static long factorial(int n) {
        if (n <= 1) return 1;
        return n * factorial(n - 1);
    }

    // 方法调用示例
    public static void main(String[] args) {
        System.out.println(add(5, 3));           // 8
        System.out.println(add(5, 3, 2));        // 10
        System.out.println(add(5.5, 3.2));       // 8.7
        System.out.println(sum(1, 2, 3, 4, 5));  // 15

        // 递归陷阱:栈溢出
        // factorial(10000);  // 可能抛出 StackOverflowError
    }
}

4.2 参数的进阶特性
默认参数与关键字参数(Python)

# 默认参数
def greet(name, greeting="Hello", punctuation="!"):
    print(f"{greeting}, {name}{punctuation}")

greet("Alice")                    # Hello, Alice!
greet("Bob", "Hi")                # Hi, Bob!
greet("Charlie", punctuation="?") # Hello, Charlie?

# 默认参数的陷阱(可变对象)
def add_item(item, lst=[]):       # 危险!默认参数在定义时计算
    lst.append(item)
    return lst

print(add_item(1))  # [1]
print(add_item(2))  # [1, 2] !不是[2]
print(add_item(3))  # [1, 2, 3]

# 正确做法
def add_item_safe(item, lst=None):
    if lst is None:
        lst = []
    lst.append(item)
    return lst

# 关键字参数
def create_user(name, age, email):
    print(f"Name: {name}, Age: {age}, Email: {email}")

create_user(age=25, name="Alice", email="alice@example.com")  # 顺序任意

# 强制关键字参数(*号后的参数必须用关键字传递)
def config(host, port, *, timeout, retry):
    print(f"Host: {host}, Port: {port}, Timeout: {timeout}, Retry: {retry}")

config("localhost", 8080, timeout=30, retry=3)  # 正确
# config("localhost", 8080, 30, 3)  # 错误!

4.3 变量作用域与闭包

// JavaScript作用域与闭包示例
function outerFunction(x) {
    // 外部函数变量
    let outerVar = 10;

    // 内部函数(闭包)
    function innerFunction(y) {
        // 可以访问外部函数的变量
        console.log(x + outerVar + y);
    }

    return innerFunction;
}

const closure = outerFunction(5);
closure(3);  // 输出 18 (5+10+3)

// 经典闭包陷阱
function createCounters() {
    let counters = [];
    for (var i = 0; i < 3; i++) {  // 使用var
        counters.push(function() {
            console.log(i);
        });
    }
    return counters;
}

const counters = createCounters();
counters[0]();  // 输出 3,不是0!
counters[1]();  // 输出 3
counters[2]();  // 输出 3

// 解决方案:使用let或IIFE
function createCountersFixed() {
    let counters = [];
    for (let i = 0; i < 3; i++) {  // let有块级作用域
        counters.push(function() {
            console.log(i);
        });
    }
    return counters;
}

4.4 递归的深度解析

# 递归经典案例:汉诺塔
def hanoi(n, source, target, auxiliary):
    """
    汉诺塔递归解法
    n: 盘子数量
    source: 起始柱子
    target: 目标柱子
    auxiliary: 辅助柱子
    """
    if n == 1:
        print(f"移动盘子1从 {source} 到 {target}")
        return

    # 将n-1个盘子从source移动到auxiliary
    hanoi(n - 1, source, auxiliary, target)
    # 移动最大的盘子
    print(f"移动盘子{n}从 {source} 到 {target}")
    # 将n-1个盘子从auxiliary移动到target
    hanoi(n - 1, auxiliary, target, source)

# 测试
hanoi(3, 'A', 'C', 'B')

# 递归优化:斐波那契数列(带备忘录)
def fibonacci_memo(n, memo={}):
    if n in memo:
        return memo[n]
    if n <= 1:
        return n
    memo[n] = fibonacci_memo(n-1, memo) + fibonacci_memo(n-2, memo)
    return memo[n]

# 尾递归(Python不支持尾递归优化,仅供参考)
def factorial_tail(n, accumulator=1):
    if n == 0:
        return accumulator
    return factorial_tail(n-1, n * accumulator)

来源:
http://bncne.cn/

相关文章
|
6月前
|
边缘计算 缓存 人工智能
AIWCLOUD:免备案CDN,过移动屏蔽,不限制内容架构下的全球边缘计算
在全球化数字经济背景下,“免备案CDN”以全球PoP节点、Anycast智能路由、BBR/QUIC优化、分层缓存、边缘安全与Serverless能力,构建低延迟、高合规、强扩展的跨境网络底座,助力企业高效出海。(239字)
407 1
|
6月前
|
人工智能 API 语音技术
阿里云百炼CLI(Bailian CLI)一行指令调用阿里云百炼全模态AI能力
阿里云百炼CLI是百炼AI平台的命令行工具,支持一行指令调用全模态能力(对话、图像/视频生成、语音识别等),深度集成AI Agent,赋能Vibe Coding、Skills扩展与MCP。提供AI Agent自动安装与手动安装两种方式,开箱即用。阿里云百炼官网:https://t.aliyun.com/U/fPVHqY
563 0
|
6月前
|
人工智能 JSON 测试技术
接口自动化测试的下一个十年:从脚本到Skills,让AI学会“如何测”
本文探讨接口自动化测试的范式升级:从低效脚本维护转向AI驱动的“技能(Skills)”模式。指出脚本堆积不等于测试能力,核心在于沉淀可推理的业务规则与契约。通过三层机制(业务知识层、策略生成层、执行反馈层),实现从“执行指令”到“理解意图”的跃迁。强调测试工程师的新价值——定义“如何测”,而非写多少行代码。
|
6月前
|
Ubuntu Linux KVM
虚拟机搭建教程(二)
教程来源 https://zlpow.cn/ 本文详解Windows、Linux三大平台虚拟化实战:Windows下用VMware安装Ubuntu 24.04(含Tools与快照),VirtualBox部署CentOS Stream 9;Linux主机通过KVM命令行及virt-manager搭建高性能虚拟机,覆盖配置、联网、增强工具与管理全流程。
|
6月前
|
人工智能 API 语音技术
阿里云百炼CLI命令行工具:开源Agent可调用全套模型和应用能力
阿里云百炼CLI是百炼AI平台的开源命令行工具,支持Agent调用全模态能力(对话、图像/视频生成、语音识别、知识库检索等),提供AI编程、技能扩展、MCP集成等场景支持。安装便捷,一行指令即可启用。阿里云百炼官网:https://t.aliyun.com/U/fPVHqY
|
6月前
|
人工智能 自然语言处理 API
阿里云Token Plan 团队版:按Credits计费,标准坐席、高级坐席和尊享坐席功能额度及费用清单
阿里云百炼Token Plan团队版是面向企业/团队的AI大模型订阅服务,支持文本与图像生成模型(如Qwen3.6、Qwen-Image、Wan2.7等),按Credits统一计费;提供标准(198元/月)、高级(698元/月)、尊享(1398元/月)三档坐席,含多模型切换、工具兼容、团队管理及数据安全保护。快速开通体验:https://t.aliyun.com/U/fPVHqY
|
6月前
|
运维 Java 测试技术
程序员必备的十大技能(进阶版)之性能调优与故障排查(四)
教程来源 https://aescc.cn/ 本节系统介绍Java应用性能分析与稳定性保障核心实践:涵盖Arthas诊断、火焰图性能剖析、全链路压测方法论及JMeter实战、混沌工程故障注入(ChaosBlade),并复盘Full GC与数据库死锁两大典型故障案例,助力高效定位与解决线上性能问题。
|
6月前
|
运维 Java 程序员
程序员必备的十大技能(进阶版)之性能调优与故障排查(一)
教程来源 https://qeext.cn/ 本文系统讲解性能调优与故障排查核心技能,涵盖故障方法论、CPU/内存/I/O/网络/数据库问题定位、Java诊断工具(Arthas/JVM)、全链路压测及混沌工程,辅以实战案例与黄金排查原则,助开发者从“重启党”进阶为问题终结者。
|
6月前
|
人工智能 安全 定位技术
CodeGraph深度解析 让Claude Code工具调用直降七成的核心原理与实操教程
如今以Claude Code为代表的AI编程智能体已经成为开发者日常编码、项目重构、漏洞修复的必备工具。但在长期使用过程中,几乎所有开发者都会遇到同一个明显痛点:AI虽然具备强大的代码生成与分析能力,却常常陷入盲目探索的循环中。
2598 4
|
6月前
|
缓存 安全 算法
软件开发进阶技能之性能与安全调优(一)
本文系统讲解性能与安全调优核心技术:从算法复杂度优化、集合选型、线程池配置、锁粒度控制,到无锁编程与异步并发,结合大量Java代码示例与底层原理,助开发者构建高可靠、高可用企业级应用。