跳到主要内容

函数

函数是组织好的、可重复使用的代码块,用于实现单一或相关联的功能。

函数定义

基本语法

使用 def 关键字定义函数。

# 基本函数定义
def greet():
"""问候函数"""
print("Hello, World!")

# 调用函数
greet()

# 带参数的函数
def greet_person(name):
print(f"Hello, {name}!")

greet_person("Alice") # Hello, Alice!
greet_person("Bob") # Hello, Bob!

# 带返回值的函数
def add(a, b):
return a + b

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

函数命名规则

# 有效的函数名
def calculate_sum(): # 蛇形命名法
pass

def get_user_name(): # 动词开头
pass

def is_valid(): # 布尔值函数用 is/has/can 开头
pass

# 避免
def CalculateSum(): # 不要用帕斯卡命名
pass

def d(): # 不要用单字母(除数学函数外)
pass

def 函数(): # 不要用中文(虽然支持)
pass

文档字符串 (Docstring)

文档字符串用于描述函数的功能、参数和返回值。

def calculate_bmi(weight, height):
"""
计算身体质量指数(BMI)

Args:
weight: 体重(公斤)
height: 身高(米)

Returns:
BMI 值

Examples:
>>> calculate_bmi(70, 1.75)
22.857...
"""
return weight / (height ** 2)

# 访问文档字符串
print(calculate_bmi.__doc__)
help(calculate_bmi)

# 简单函数的文档字符串
def greet(name):
"""向指定的人问好"""
print(f"Hello, {name}!")

# 多行文档字符串
def process_data(data, verbose=False):
"""
处理数据集

参数:
data: 要处理的数据列表
verbose: 是否显示详细信息(默认False)

返回:
处理后的数据列表

异常:
ValueError: 当数据为空时
"""
if not data:
raise ValueError("数据不能为空")
# 处理逻辑...

函数调用

# 定义多个函数
def greet():
print("Hello!")

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

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

# 函数调用
greet() # Hello!
result = add(3, 5) # 8
product = multiply(2, 3, 4) # 24

# 函数作为表达式的一部分
print(add(5, 10) * 2) # 30

# 嵌套调用
result = add(add(1, 2), add(3, 4)) # 10

# 函数必须先定义后调用
# greet_early() # 报错:函数未定义

def greet_early():
print("Early greeting!")

greet_early() # 正确

参数

Python 函数支持多种参数类型,提供灵活的调用方式。

位置参数

位置参数按照定义的顺序传递。

def describe_person(name, age, city):
print(f"{name} 今年 {age} 岁,来自 {city}")

# 调用时按顺序传递
describe_person("Alice", 25, "New York")
# 输出: Alice 今年 25 岁,来自 New York

describe_person("Bob", 30, "London")
# 输出: Bob 今年 30 岁,来自 London

# 错误:参数数量不匹配
# describe_person("Charlie", 35) # 报错:缺少参数

# 错误:参数顺序错误
describe_person(25, "Alice", "New York")
# 输出: 25 今年 Alice 岁,来自 New York(语义错误)

关键字参数

使用参数名传递参数,可以不按顺序。

def describe_person(name, age, city):
print(f"{name} 今年 {age} 岁,来自 {city}")

# 使用关键字参数
describe_person(name="Alice", age=25, city="New York")
describe_person(age=30, name="Bob", city="London") # 顺序可变

# 混合使用(位置参数必须在前面)
describe_person("Charlie", age=35, city="Paris")
# describe_person(name="David", 40, "Berlin") # 错误:位置参数在关键字参数后

# 提高代码可读性
# 不推荐
connect("localhost", 8080, True, 30)

# 推荐
connect(host="localhost", port=8080, ssl=True, timeout=30)

默认参数

在定义时为参数指定默认值。

def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")

greet("Alice") # Hello, Alice!
greet("Bob", "Hi") # Hi, Bob!
greet("Charlie", "Good morning") # Good morning, Charlie!

# 多个默认参数
def create_user(name, role="user", active=True):
return {
"name": name,
"role": role,
"active": active
}

print(create_user("Alice"))
# {'name': 'Alice', 'role': 'user', 'active': True}

print(create_user("Bob", role="admin"))
# {'name': 'Bob', 'role': 'admin', 'active': True}

print(create_user("Charlie", active=False))
# {'name': 'Charlie', 'role': 'user', 'active': False}

# 注意:默认参数只计算一次
def append_to_list(value, lst=[]): # 危险的默认可变参数
lst.append(value)
return lst

print(append_to_list(1)) # [1]
print(append_to_list(2)) # [1, 2](使用同一个列表!)

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

print(append_to_list(1)) # [1]
print(append_to_list(2)) # [2]

可变参数

允许函数接收任意数量的参数。

*args(位置可变参数)

# *args 接收任意数量的位置参数(作为元组)
def sum_all(*args):
print(f"参数类型: {type(args)}") # <class 'tuple'>
return sum(args)

print(sum_all(1, 2, 3)) # 6
print(sum_all(1, 2, 3, 4, 5)) # 15
print(sum_all()) # 0

# 混合使用
def describe(name, *args):
print(f"Name: {name}")
print(f"Skills: {args}")

describe("Alice", "Python", "Java", "SQL")
# Name: Alice
# Skills: ('Python', 'Java', 'SQL')

# 实际应用:计算平均值
def average(*numbers):
if not numbers:
return 0
return sum(numbers) / len(numbers)

print(average(1, 2, 3, 4, 5)) # 3.0

**kwargs(关键字可变参数)

# **kwargs 接收任意数量的关键字参数(作为字典)
def print_info(**kwargs):
print(f"参数类型: {type(kwargs)}") # <class 'dict'>
for key, value in kwargs.items():
print(f"{key}: {value}")

print_info(name="Alice", age=25, city="New York")
# name: Alice
# age: 25
# city: New York

# 混合使用
def create_profile(name, **kwargs):
profile = {"name": name}
profile.update(kwargs)
return profile

print(create_profile("Alice", age=25, city="NY", country="USA"))
# {'name': 'Alice', 'age': 25, 'city': 'NY', 'country': 'USA'}

# 实际应用:配置函数
def configure(**settings):
config = {
"debug": False,
"log_level": "INFO",
"max_connections": 10
}
config.update(settings)
return config

print(configure(debug=True, max_connections=50))
# {'debug': True, 'log_level': 'INFO', 'max_connections': 50}

参数顺序规则

# 参数顺序:位置 -> 默认 -> *args -> **kwargs
def function(arg1, arg2, default_arg="default", *args, **kwargs):
print(f"arg1: {arg1}")
print(f"arg2: {arg2}")
print(f"default_arg: {default_arg}")
print(f"args: {args}")
print(f"kwargs: {kwargs}")

function(1, 2, 3, 4, 5, key1="value1", key2="value2")
# arg1: 1
# arg2: 2
# default_arg: 3
# args: (4, 5)
# kwargs: {'key1': 'value1', 'key2': 'value2'}

# 实际应用示例
def log(message, level="INFO", *args, **kwargs):
print(f"[{level}] {message}")
if args:
print(f"Additional args: {args}")
if kwargs:
print(f"Additional kwargs: {kwargs}")

log("System started")
log("User logged in", "DEBUG")
log("Error occurred", "ERROR", "details", "here")
log("Warning", "WARNING", timeout=30, retry=True)

参数解包

将列表/元组或字典解包为参数。

# 列表/元组解包(使用 *)
def add(a, b, c):
return a + b + c

numbers = [1, 2, 3]
print(add(*numbers)) # 6

# 等价于
print(add(numbers[0], numbers[1], numbers[2]))

# 字典解包(使用 **)
def greet(name, age, city):
print(f"{name}, {age}, {city}")

person = {"name": "Alice", "age": 25, "city": "New York"}
greet(**person) # Alice, 25, New York

# 等价于
greet(name="Alice", age=25, city="New York")

# 混合使用
def function(a, b, c, d, e):
print(a, b, c, d, e)

nums = [1, 2]
more_nums = {"c": 3, "d": 4, "e": 5}
function(*nums, **more_nums) # 1 2 3 4 5

# 实际应用:函数式编程
operations = [
(add, (1, 2, 3)),
(lambda x, y: x * y, (4, 5))
]

for func, args in operations:
result = func(*args)
print(result) # 6, 20

强制关键字参数

强制某些参数必须使用关键字参数传递。

# Python 3.0+: 使用 * 作为分隔
def function(a, b, *, c, d):
print(a, b, c, d)

function(1, 2, c=3, d=4) # 正确
# function(1, 2, 3, 4) # 错误:c 和 d 必须是关键字参数

# Python 3.8+: 仅限关键字参数
def greet(name, *, greeting="Hello"):
print(f"{greeting}, {name}!")

greet("Alice") # Hello, Alice!
greet("Bob", greeting="Hi") # Hi, Bob!
# greet("Charlie", "Hey") # 错误

# 实际应用:避免参数混淆
def connect(host, port, *, username, password):
print(f"Connecting to {host}:{port} as {username}")

connect("localhost", 8080, username="admin", password="secret")
# 正确且清晰

# connect("localhost", 8080, "admin", "secret")
# 错误:容易混淆

返回值

return 语句

return 语句用于从函数返回值并退出函数。

# 返回单个值
def add(a, b):
return a + b

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

# 返回多个值(实际返回元组)
def get_user_info():
name = "Alice"
age = 25
city = "New York"
return name, age, city

# 接收多个返回值
name, age, city = get_user_info()
print(name, age, city) # Alice 25 New York

# 作为元组接收
info = get_user_info()
print(info) # ('Alice', 25, 'New York')

# 返回不同类型
def get_data():
return [1, 2, 3], {"key": "value"}, "string"

data1, data2, data3 = get_data()
print(data1) # [1, 2, 3]
print(data2) # {'key': 'value'}
print(data3) # string

# 提前返回
def divide(a, b):
if b == 0:
return "错误:除数不能为零"
return a / b

print(divide(10, 2)) # 5.0
print(divide(10, 0)) # 错误:除数不能为零

返回 None

函数没有 return 语句或 return 后没有值时,返回 None。

# 没有 return 语句
def greet(name):
print(f"Hello, {name}!")

result = greet("Alice")
print(result) # None

# return 后没有值
def return_none():
return

result = return_none()
print(result) # None

# 显式返回 None
def check_positive(number):
if number > 0:
return True
return None

result = check_positive(-5)
print(result) # None

# 实际应用:条件返回
def find_item(lst, target):
for item in lst:
if item == target:
return item
return None # 未找到

items = ["apple", "banana", "orange"]
print(find_item(items, "banana")) # banana
print(find_item(items, "grape")) # None

返回函数

函数可以返回另一个函数。

# 返回函数
def create_multiplier(factor):
def multiply(x):
return x * factor
return multiply

times3 = create_multiplier(3)
times5 = create_multiplier(5)

print(times3(10)) # 30
print(times5(10)) # 50

# 实际应用:函数工厂
def power(exponent):
def raise_to(x):
return x ** exponent
return raise_to

square = power(2)
cube = power(3)

print(square(4)) # 16
print(cube(4)) # 64

# 返回 lambda 函数
def make_comparator(operator):
if operator == ">":
return lambda a, b: a > b
elif operator == "<":
return lambda a, b: a < b
else:
return lambda a, b: a == b

greater_than = make_comparator(">")
print(greater_than(5, 3)) # True

作用域

变量的作用域决定了变量在哪些地方可以被访问。

局部变量

在函数内部定义的变量。

def my_function():
local_var = "局部变量"
print(local_var) # 可以访问

my_function()
# print(local_var) # 错误:函数外部无法访问

def calculate():
x = 10
y = 20
return x + y

result = calculate()
# print(x, y) # 错误:x 和 y 是局部变量

全局变量

在模块级别定义的变量,可以在整个模块中访问。

# 全局变量
global_var = "全局变量"

def access_global():
print(global_var) # 可以访问

access_global() # 全局变量

def modify_global_wrong():
global_var = "局部变量" # 创建新的局部变量
print(global_var)

modify_global_wrong() # 局部变量
print(global_var) # 全局变量(未被修改)

# 使用 global 关键字修改全局变量
count = 0

def increment():
global count
count += 1

increment()
increment()
print(count) # 2

# 实际应用:配置变量
DEBUG = True

def log(message):
if DEBUG:
print(f"[DEBUG] {message}")

log("Starting application") # [DEBUG] Starting application

DEBUG = False
log("Application stopped") # 不输出

嵌套作用域

在嵌套函数中访问外层函数的变量。

def outer_function():
outer_var = "外层变量"

def inner_function():
print(outer_var) # 可以访问外层变量

inner_function()

outer_function() # 外层变量

# 修改外层变量(使用 nonlocal)
def counter():
count = 0

def increment():
nonlocal count
count += 1
return count

return increment

c = counter()
print(c()) # 1
print(c()) # 2
print(c()) # 3

# 实际应用:闭包
def make_multiplier(factor):
def multiply(number):
return number * factor
return multiply

times3 = make_multiplier(3)
print(times3(10)) # 30

LEGB 规则

Python 按照以下顺序查找变量:

# L (Local) - 局部作用域
# E (Enclosing) - 嵌套作用域
# G (Global) - 全局作用域
# B (Built-in) - 内置作用域

x = "全局" # Global

def outer():
x = "外层" # Enclosing

def inner():
x = "局部" # Local
print(x) # 输出: 局部

inner()
print(x) # 输出: 外层

outer()
print(x) # 输出: 全局

# 查找顺序示例
x = "global"

def test():
# x = "enclosing" # 注释掉
def inner():
# x = "local" # 注释掉
print(x) # 查找顺序:Local -> Enclosing -> Global -> Built-in

inner()

test() # global

# 内置作用域
def len(x): # 遮蔽内置函数
return "自定义的 len"

print(len([1, 2, 3])) # 自定义的 len

global 和 nonlocal

# global:声明使用全局变量
count = 0

def increment():
global count
count += 1
return count

print(increment()) # 1
print(count) # 1

# nonlocal:声明使用外层函数的变量
def outer():
x = 10

def inner():
nonlocal x
x += 5
return x

return inner()

print(outer()) # 15

# 对比
x = 10 # 全局

def outer():
x = 20 # 外层

def inner():
global x # 使用全局变量
x += 5
return x

result = inner()
print(f"inner: {result}") # 15
print(f"outer: {x}") # 20

outer()
print(f"global: {x}") # 15

# 正确使用
def outer2():
x = 20 # 外层

def inner2():
nonlocal x # 使用外层变量
x += 5
return x

result = inner2()
print(f"inner2: {result}") # 25
print(f"outer2: {x}") # 25

outer2()

Lambda表达式

Lambda表达式(匿名函数)是简洁的单行函数。

基本语法

# 基本形式:lambda parameters: expression
# lambda 函数自动返回表达式的值

# 普通函数
def add(a, b):
return a + b

# 等价的 lambda 函数
add_lambda = lambda a, b: a + b

print(add(3, 5)) # 8
print(add_lambda(3, 5)) # 8

# 多个参数
multiply = lambda x, y, z: x * y * z
print(multiply(2, 3, 4)) # 24

# 无参数
greet = lambda: "Hello, World!"
print(greet()) # Hello, World!

# 立即执行(IIFE)
result = (lambda x: x ** 2)(5)
print(result) # 25

Lambda 的限制

# Lambda 只能包含表达式,不能包含语句
# 有效
valid_lambda = lambda x: x * 2

# 无效
# invalid_lambda = lambda x:
# if x > 0:
# return x
# else:
# return -x

# 但可以使用条件表达式
abs_value = lambda x: x if x >= 0 else -x
print(abs_value(-5)) # 5
print(abs_value(5)) # 5

# 不能包含多个表达式
# invalid = lambda x: print(x); return x * 2

# 但可以使用复杂表达式
complex_lambda = lambda x: (x ** 2 if x > 0 else -x, x * 2)
print(complex_lambda(3)) # (9, 6)

高阶函数中的 Lambda

# map:对序列中每个元素应用函数
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16, 25]

# filter:过滤序列中的元素
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6, 8, 10]

# reduce:归约序列
from functools import reduce
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
print(total) # 15

# sorted:自定义排序
students = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 20},
{"name": "Charlie", "age": 30}
]
sorted_students = sorted(students, key=lambda s: s["age"])
print(sorted_students)
# [{'name': 'Bob', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Charlie', 'age': 30}]

Lambda 的使用场景

# 1. 简单的回调函数
def process(value, callback):
return callback(value)

print(process(10, lambda x: x ** 2)) # 100
print(process(10, lambda x: x * 2)) # 20

# 2. GUI 编程中的事件处理
# button.on_click(lambda event: print("Clicked!"))

# 3. 排序键函数
words = ["apple", "banana", "cherry", "date"]
sorted_by_length = sorted(words, key=lambda word: len(word))
print(sorted_by_length) # ['date', 'apple', 'banana', 'cherry']

# 4. 数据转换
data = [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}]
names = list(map(lambda person: person["name"], data))
print(names) # ['Alice', 'Bob']

# 5. 条件过滤
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
divisible_by_3 = list(filter(lambda x: x % 3 == 0, numbers))
print(divisible_by_3) # [3, 6, 9]

Lambda vs 普通函数

# Lambda 适合:简单、一次性使用的函数
# 普通函数适合:复杂、可重用的函数

# 使用 Lambda(简单)
short = lambda x: x * 2

# 使用普通函数(复杂)
def complex_operation(x):
"""执行复杂的计算"""
if x < 0:
return 0
elif x < 10:
return x * 2
else:
return x ** 2

# 可读性对比
# Lambda(不易读)
result = (lambda x: x ** 2 if x > 0 else -x)(5)

# 普通函数(易读)
def abs_square(x):
if x > 0:
return x ** 2
return -x

result = abs_square(5)

内置函数

Python 提供了许多内置函数,可以直接使用。

数学相关

# abs() - 绝对值
print(abs(-10)) # 10

# round() - 四舍五入
print(round(3.14159, 2)) # 3.14
print(round(3.5)) # 4

# pow() - 幂运算
print(pow(2, 3)) # 8
print(pow(2, 3, 5)) # 8 % 5 = 3(带模数)

# sum() - 求和
print(sum([1, 2, 3, 4, 5])) # 15

# max() / min() - 最大值/最小值
print(max([1, 5, 3, 9, 2])) # 9
print(min([1, 5, 3, 9, 2])) # 1

# 带键函数
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
print(max(students, key=lambda s: s[1])) # ('Bob', 92)

类型转换

# int() - 转换为整数
print(int("123")) # 123
print(int(3.14)) # 3

# float() - 转换为浮点数
print(float("3.14")) # 3.14

# str() - 转换为字符串
print(str(123)) # '123'

# list() - 转换为列表
print(list("hello")) # ['h', 'e', 'l', 'l', 'o']

# tuple() - 转换为元组
print(tuple([1, 2, 3])) # (1, 2, 3)

# set() - 转换为集合
print(set([1, 2, 2, 3])) # {1, 2, 3}

# dict() - 转换为字典
print(dict([("a", 1), ("b", 2)])) # {'a': 1, 'b': 2}

序列操作

# len() - 获取长度
print(len([1, 2, 3, 4, 5])) # 5

# sorted() - 返回新列表
numbers = [3, 1, 4, 1, 5, 9]
print(sorted(numbers)) # [1, 1, 3, 4, 5, 9]

# reversed() - 反转迭代器
print(list(reversed([1, 2, 3]))) # [3, 2, 1]

# enumerate() - 获取索引和值
for index, value in enumerate(["a", "b", "c"]):
print(index, value)
# 0 a
# 1 b
# 2 c

# zip() - 组合序列
names = ["Alice", "Bob"]
ages = [25, 30]
print(list(zip(names, ages))) # [('Alice', 25), ('Bob', 30)]

# range() - 生成数字序列
print(list(range(5))) # [0, 1, 2, 3, 4]

高阶函数

# map() - 应用函数到每个元素
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16, 25]

# filter() - 过滤元素
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6]

# reduce() - 归约
from functools import reduce
numbers = [1, 2, 3, 4]
total = reduce(lambda x, y: x + y, numbers)
print(total) # 10

# any() / all() - 检查元素
print(any([False, False, True])) # True
print(all([True, True, False])) # False

# 实际应用
numbers = [1, 2, 3, 4, 5]
print(all(n > 0 for n in numbers)) # True(所有正数)
print(any(n > 10 for n in numbers)) # False(没有大于10的)

输入输出

# print() - 输出
print("Hello, World!")
print("Name:", "Alice", "Age:", 25) # 多个参数
print("Hello", end=" ") # 不换行
print("World")

# input() - 输入
name = input("请输入名字: ")
print(f"你好, {name}!")

# 格式化输出
name = "Alice"
age = 25
print(f"姓名: {name}, 年龄: {age}") # f-string
print("姓名: {}, 年龄: {}".format(name, age)) # format

迭代器和属性

# iter() / next() - 迭代器协议
numbers = [1, 2, 3]
it = iter(numbers)
print(next(it)) # 1
print(next(it)) # 2
print(next(it)) # 3

# id() - 对象标识
x = [1, 2, 3]
y = x
print(id(x) == id(y)) # True

# type() - 类型
print(type(123)) # <class 'int'>
print(type([1, 2, 3])) # <class 'list'>

# isinstance() - 类型检查
print(isinstance(123, int)) # True
print(isinstance([1, 2, 3], list)) # True

# hasattr() / getattr() / setattr() - 属性操作
class Person:
def __init__(self, name):
self.name = name

person = Person("Alice")
print(hasattr(person, "name")) # True
print(getattr(person, "name")) # Alice
setattr(person, "age", 25)
print(person.age) # 25

其他常用函数

# help() - 帮助
# help(print)

# dir() - 列出属性
print(dir([])) # 列表的所有方法和属性

# eval() - 执行表达式
result = eval("2 + 3 * 4")
print(result) # 14

# exec() - 执行代码
# exec("print('Hello')")

# compile() - 编译代码
code = compile("print('Hello')", "<string>", "exec")
exec(code)

# open() - 打开文件
# file = open("test.txt", "r")
# content = file.read()
# file.close()

# hash() - 哈希值
print(hash("hello")) # 字符串的哈希值

# callable() - 检查是否可调用
def func():
pass

print(callable(func)) # True
print(callable(123)) # False

函数最佳实践

1. 函数应该短小精悍

# 不推荐:函数太长
def process_user(data):
# 100 行代码...
pass

# 推荐:拆分为多个小函数
def validate_user(data):
"""验证用户数据"""
pass

def save_user(data):
"""保存用户数据"""
pass

def send_notification(user):
"""发送通知"""
pass

def process_user(data):
"""处理用户数据"""
validate_user(data)
save_user(data)
send_notification(data)

2. 单一职责原则

# 不推荐:函数做太多事情
def process_and_save_and_notify(data):
# 处理
# 保存
# 通知
pass

# 推荐:每个函数只做一件事
def process_data(data):
"""处理数据"""
pass

def save_data(data):
"""保存数据"""
pass

def send_notification(message):
"""发送通知"""
pass

3. 使用有意义的函数名和参数名

# 不推荐
def f(x, y):
return x * y

# 推荐
def calculate_area(width, height):
"""计算矩形面积"""
return width * height

4. 编写文档字符串

# 推荐
def calculate_discount(price, discount_rate):
"""
计算折扣后的价格

Args:
price: 原价
discount_rate: 折扣率(0-1之间)

Returns:
折扣后的价格

Raises:
ValueError: 当折扣率不在0-1之间时

Examples:
>>> calculate_discount(100, 0.2)
80.0
"""
if not 0 <= discount_rate <= 1:
raise ValueError("折扣率必须在0-1之间")
return price * (1 - discount_rate)

5. 避免使用可变默认参数

# 不推荐
def add_item(item, lst=[]):
lst.append(item)
return lst

# 推荐
def add_item(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst

6. 使用类型提示

# 推荐
from typing import List, Optional

def calculate_sum(numbers: List[int]) -> int:
"""计算数字列表的总和"""
return sum(numbers)

def find_user(user_id: int) -> Optional[dict]:
"""根据ID查找用户"""
# 返回用户字典或 None
pass

def greet(name: str = "World") -> str:
"""生成问候语"""
return f"Hello, {name}!"

7. 返回一致的结果

# 不推荐:返回类型不一致
def get_data(condition):
if condition:
return [1, 2, 3]
else:
return None

# 推荐:始终返回相同类型
from typing import List, Optional

def get_data(condition) -> Optional[List[int]]:
if condition:
return [1, 2, 3]
else:
return []

小结

本章节介绍了 Python 的函数:

  • 函数定义: def 关键字, 文档字符串, 函数命名
  • 参数: 位置参数, 关键字参数, 默认参数, 可变参数, 参数解包, 强制关键字参数
  • 返回值: return 语句, 多返回值, 返回 None, 返回函数
  • 作用域: 局部变量, 全局变量, 嵌套作用域, LEGB 规则, global 和 nonlocal
  • Lambda表达式: 匿名函数, 高阶函数, 使用场景
  • 内置函数: 数学函数, 类型转换, 序列操作, 高阶函数, 输入输出

掌握函数是编写模块化和可维护代码的关键。下一章我们将学习面向对象编程,包括类、对象、继承、多态等。