Skip to content

1. 函数基础

1-1. 函数定义

函数是组织好的、可重复使用的代码块,用于实现特定功能。

python
# 基本函数定义
def greet(name):
    return f"Hello, {name}!"

# 无参数函数
def say_hello():
    print("Hello, World!")

# 多参数函数
def add(a, b):
    return a + b

1-2. 函数调用

python
# 调用函数
result = greet("John")
print(result)  # Hello, John!

# 直接调用
say_hello()  # Hello, World!

# 使用返回值
sum_result = add(5, 3)
print(sum_result)  # 8

2. 函数参数

2-1. 参数类型

  1. 位置参数
python
def power(base, exponent):
    return base ** exponent

result = power(2, 3)  # 8
  1. 默认参数
python
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("John"))           # Hello, John!
print(greet("John", "Hi"))     # Hi, John!
  1. 关键字参数
python
def create_user(name, age, city):
    return {"name": name, "age": age, "city": city}

user = create_user(name="John", age=25, city="New York")
  1. 可变参数
python
def sum_numbers(*numbers):
    return sum(numbers)

print(sum_numbers(1, 2, 3, 4, 5))  # 15

TIP

类似于 JavaScript 中的 arguments 对象,Python 中的 *args**kwargs 可以接收任意数量的参数。

  1. 关键字可变参数
python
def print_info(**info):
    for key, value in info.items():
        print(f"{key}: {value}")

print_info(name="John", age=25, city="New York")

2-2. 参数顺序

参数定义的顺序:

  1. 位置参数
  2. 默认参数
  3. 可变参数
  4. 关键字参数
  5. 关键字可变参数
python
def complex_function(pos1, pos2, default1="value1", default2="value2", *args, **kwargs):
    print(f"位置参数: {pos1}, {pos2}")
    print(f"默认参数: {default1}, {default2}")
    print(f"可变参数: {args}")
    print(f"关键字参数: {kwargs}")

3. 函数返回值

3-1. 基本返回值

python
def square(n):
    return n * n

result = square(4)  # 16

3-2. 多值返回

python
def get_coordinates():
    return 10, 20

x, y = get_coordinates()
print(x, y)  # 10 20

3-3. 条件返回

python
def absolute(n):
    if n >= 0:
        return n
    return -n

4. 函数作用域

4-1. 局部作用域

python
def calculate():
    x = 10  # 局部变量
    return x

# print(x)  # 错误:x 未定义

4-2. 全局作用域

python
x = 100  # 全局变量

def modify_global():
    global x
    x = 200

print(x)  # 100
modify_global()
print(x)  # 200

4-3. 嵌套作用域

python
def outer():
    x = 10
    
    def inner():
        print(x)  # 可以访问外部函数的变量
    
    inner()

outer()  # 10

5. 函数高级特性

5-1. 函数作为参数

python
def apply_operation(func, x, y):
    return func(x, y)

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

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

print(apply_operation(add, 5, 3))      # 8
print(apply_operation(multiply, 5, 3)) # 15

5-2. 闭包

python
def create_counter():
    count = 0
    
    def counter():
        nonlocal count
        count += 1
        return count
    
    return counter

counter = create_counter()
print(counter())  # 1
print(counter())  # 2

5-3. 装饰器

python
def timer(func):
    def wrapper(*args, **kwargs):
        import time
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"函数执行时间: {end - start}秒")
        return result
    return wrapper

@timer
def slow_function():
    import time
    time.sleep(1)
    return "完成"

result = slow_function()

6. 内置函数

6-1. 常用内置函数

python
# 类型转换
int("123")      # 123
float("3.14")   # 3.14
str(123)        # "123"
bool(1)         # True

# 序列操作
len([1, 2, 3])  # 3
max(1, 2, 3)    # 3
min(1, 2, 3)    # 1
sum([1, 2, 3])  # 6

# 其他
print("Hello")  # 输出
input("请输入: ")  # 输入

7. 函数最佳实践

7-1. 函数设计原则

  1. 单一职责

    • 每个函数只做一件事
    • 保持函数简单明确
  2. 参数设计

    • 使用有意义的参数名
    • 合理使用默认参数
    • 避免过多参数
  3. 返回值设计

    • 返回类型要一致
    • 使用有意义的返回值

7-2. 文档字符串

python
def calculate_average(numbers):
    """
    计算数字列表的平均值
    
    参数:
        numbers (list): 数字列表
    
    返回:
        float: 平均值
    
    异常:
        ValueError: 当列表为空时
    """
    if not numbers:
        raise ValueError("列表不能为空")
    return sum(numbers) / len(numbers)

7-3. 错误处理

python
def safe_divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return "除数不能为零"
    except TypeError:
        return "参数类型错误"

8. 函数调试

8-1. 使用 print 调试

python
def complex_function(x):
    print(f"输入值: {x}")
    result = x * 2
    print(f"计算结果: {result}")
    return result

8-2. 使用断言

python
def calculate_square(n):
    assert isinstance(n, (int, float)), "输入必须是数字"
    assert n >= 0, "输入必须是非负数"
    return n * n

8-3. 使用日志

python
import logging

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

def process_data(data):
    logger.debug(f"开始处理数据: {data}")
    result = data * 2
    logger.debug(f"处理结果: {result}")
    return result