本文目录导读:

在Python中,定义函数方法有多种方式,我来为你详细介绍:
基本函数定义
# 基本语法
def function_name(parameters):
"""函数文档字符串"""
# 函数体
return result
# 示例1:无参数函数
def greet():
print("Hello!")
# 示例2:带参数的函数
def add(x, y):
return x + y
# 调用函数
greet() # 输出: Hello!
result = add(3, 5)
print(result) # 输出: 8
不同类型的参数
# 默认参数
def power(x, n=2):
"""计算x的n次方,默认平方"""
return x ** n
print(power(3)) # 9 (3²)
print(power(3, 3)) # 27 (3³)
# 可变参数 *args
def sum_all(*args):
"""接收任意数量的参数"""
return sum(args)
print(sum_all(1, 2, 3, 4)) # 10
# 关键字参数 **kwargs
def print_info(**kwargs):
"""接收任意数量的关键字参数"""
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25, city="Beijing")
# 混合使用
def complex_func(a, b, *args, **kwargs):
print(f"a={a}, b={b}")
print(f"args={args}")
print(f"kwargs={kwargs}")
complex_func(1, 2, 3, 4, x=5, y=6)
返回值
# 单返回值
def square(x):
return x ** 2
# 多返回值(返回元组)
def min_max(lst):
return min(lst), max(lst)
result = min_max([3, 1, 4, 1, 5])
print(result) # (1, 5)
min_val, max_val = min_max([3, 1, 4, 1, 5])
print(min_val, max_val) # 1 5
# 无返回值(返回None)
def print_msg(msg):
print(msg)
# 函数结束,隐式返回None
result = print_msg("Hello")
print(result) # None
类型注解(Python 3.x)
def add(x: int, y: int) -> int:
"""类型注解,提高代码可读性"""
return x + y
def greet(name: str) -> str:
return f"Hello, {name}"
# 可选类型
from typing import Optional, List, Dict
def process_data(data: List[int]) -> Optional[Dict[str, int]]:
if not data:
return None
return {"sum": sum(data), "count": len(data)}
匿名函数(lambda)
# 基本lambda函数
square = lambda x: x ** 2
print(square(5)) # 25
# 多参数lambda
add = lambda x, y: x + y
print(add(3, 4)) # 7
# 在函数中使用lambda
def apply_func(func, value):
return func(value)
print(apply_func(lambda x: x * 2, 5)) # 10
# lambda在排序中的应用
students = [("Alice", 20), ("Bob", 18), ("Charlie", 22)]
students.sort(key=lambda student: student[1]) # 按年龄排序
print(students)
实战案例
# 案例1:计算器
def calculator():
"""简单的计算器"""
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:
return "Error: Division by zero"
return a / b
operations = {
'+': add,
'-': subtract,
'*': multiply,
'/': divide
}
while True:
print("\nOptions:")
print("Enter '+' for addition")
print("Enter '-' for subtraction")
print("Enter '*' for multiplication")
print("Enter '/' for division")
print("Enter 'q' to quit")
choice = input(": ")
if choice == 'q':
break
if choice in operations:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
result = operations[choice](num1, num2)
print(f"Result: {result}")
else:
print("Invalid input")
# 案例2:数据处理器
class DataProcessor:
"""数据处理类"""
@staticmethod
def clean_data(data):
"""清理数据"""
return [x for x in data if x is not None]
@classmethod
def from_string(cls, data_string):
"""从字符串创建实例"""
data = [float(x) for x in data_string.split(',')]
return cls(data)
def __init__(self, data):
self.data = data
def transform(self, func):
"""应用转换函数"""
return [func(x) for x in self.data]
def aggregate(self, func, initial=0):
"""聚合操作"""
result = initial
for item in self.data:
result = func(result, item)
return result
# 使用示例
processor = DataProcessor([1, 2, 3, 4, 5])
print(processor.transform(lambda x: x * 2)) # [2, 4, 6, 8, 10]
print(processor.aggregate(lambda x, y: x + y)) # 15
递归函数
def factorial(n):
"""计算阶乘"""
if n <= 1:
return 1
return n * factorial(n - 1)
def fibonacci(n):
"""计算斐波那契数列"""
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
# 带缓存的递归(优化)
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci_cached(n):
if n <= 1:
return n
return fibonacci_cached(n - 1) + fibonacci_cached(n - 2)
print(factorial(5)) # 120
print(fibonacci_cached(10)) # 55
最佳实践
# 1. 函数应该做一件事,并做好
def validate_email(email):
"""验证邮箱格式"""
return '@' in email and '.' in email.split('@')[-1]
# 2. 使用有意义的名称
def calculate_average_grade(grades):
return sum(grades) / len(grades)
# 3. 保持函数简短
def process_user_data(user_data):
"""处理用户数据的主函数"""
cleaned_data = clean_data(user_data)
validated_data = validate_data(cleaned_data)
return save_to_database(validated_data)
# 4. 提供文档字符串
def complex_operation(x: float, y: float) -> float:
"""
执行复杂数学运算
Args:
x: 第一个参数
y: 第二个参数
Returns:
计算结果
Raises:
ValueError: 如果输入无效
"""
if x < 0 or y < 0:
raise ValueError("参数必须为正数")
return (x + y) * (x - y)
这些是Python中定义函数的主要方式,根据你的具体需求,选择合适的方式来组织代码,好的函数设计应该遵循单一职责原则,保持清晰、可维护。