Python函数通过def定义,支持多种参数类型和return语句返回结果,合理使用可提升代码复用性与可维护性。

在Python中定义函数,核心就是使用
def
说起Python的函数定义,这几乎是我们编写任何稍复杂程序的基础。我个人觉得,它就像是把一大堆零散的工具分类打包,每次需要某个特定功能时,直接拿来用就行,省去了重复劳动的麻烦。
最基本的结构是这样的:
def my_first_function():
"""这是一个非常简单的函数,它什么也不做,只是打印一句话。"""
print("Hello from my first Python function!")
# 调用函数
my_first_function()这里,
def
my_first_function
()
:
立即学习“Python免费学习笔记(深入)”;
如果我们想让函数接收一些数据进行处理,就需要用到参数:
def greet(name):
"""根据传入的名字,打印一句问候语。"""
print(f"你好,{name}!很高兴认识你。")
greet("Alice") # 输出:你好,Alice!很高兴认识你。
greet("Bob") # 输出:你好,Bob!很高兴认识你。参数
name
greet("Alice")"Alice"
name
函数不仅能执行操作,还能把处理结果“送”出来,这就是
return
def add(a, b):
"""计算两个数的和并返回结果。"""
result = a + b
return result
sum_result = add(5, 3)
print(f"5 + 3 = {sum_result}") # 输出:5 + 3 = 8return result
result
return
return
None
有时候,我也会在函数定义时加上文档字符串(docstring),就是代码示例中三引号括起来的部分。这对于团队协作或者自己以后回顾代码时,简直是救命稻草,能快速了解函数是干嘛的,怎么用。
在Python里,函数的参数玩法非常多,这也是它灵活性的一个体现。刚开始接触可能会觉得有点乱,但掌握了之后,你会发现它们能解决很多实际问题。
位置参数 (Positional Arguments):这是最常见的。调用函数时,参数的顺序必须和定义时一致。
def describe_person(name, age):
print(f"{name}今年{age}岁。")
describe_person("张三", 30)
# describe_person(30, "李四") # 这就会出错,因为顺序反了关键字参数 (Keyword Arguments):调用函数时,通过
参数名=值
def describe_person(name, age):
print(f"{name}今年{age}岁。")
describe_person(age=25, name="小红") # 顺序无所谓默认参数 (Default Arguments):在定义函数时给参数一个默认值。如果调用时没有传入这个参数,就会使用默认值。这在我写一些通用工具函数时特别有用,可以简化调用。
def send_message(message, recipient="所有人"):
print(f"发送消息 '{message}' 给 {recipient}。")
send_message("会议通知") # recipient 使用默认值 "所有人"
send_message("紧急通知", "项目组") # recipient 被覆盖为 "项目组"一个小提醒:默认参数的值只会在函数定义时计算一次。如果默认值是一个可变对象(如列表、字典),多次调用且不传入该参数时,可能会导致意想不到的行为。
*可变位置参数 (`args
)**:当你不确定函数会接收多少个位置参数时,可以用
def calculate_sum(*numbers):
total = 0
for num in numbers:
total += num
return total
print(calculate_sum(1, 2, 3)) # 输出 6
print(calculate_sum(10, 20, 30, 40)) # 输出 100可变关键字参数 (`kwargs
)**:类似
,
def show_profile(**details):
print("个人信息:")
for key, value in details.items():
print(f" {key}: {value}")
show_profile(name="王五", age=28, city="北京")仅位置参数 (Positional-only Arguments, Python 3.8+):使用
/
/
def create_user(username, password, /, email):
print(f"创建用户: {username}, 密码: {password}, 邮箱: {email}")
create_user("user1", "pass123", email="user1@example.com")
# create_user(username="user1", password="pass123", email="user1@example.com") # 会报错这在某些API设计中很有用,比如你希望强制用户按特定顺序传入核心参数。
仅关键字参数 (Keyword-only Arguments, Python 3+):使用
*
*
def configure_settings(config_file, *, debug=False, log_level="INFO"):
print(f"配置文件: {config_file}, 调试模式: {debug}, 日志级别: {log_level}")
configure_settings("app.conf", debug=True)
# configure_settings("app.conf", True) # 会报错这有助于提高函数的健壮性和清晰度,避免参数顺序混淆。
理解这些参数类型,可以让你在编写函数时有更多的选择,设计出更灵活、更易用的接口。
写代码不只是让它能跑起来,更重要的是让它“活”得久,好理解,好修改。在我多年的编码经验里,有几个原则是我一直努力遵循的,尤其是在函数设计上。
单一职责原则 (Single Responsibility Principle, SRP):一个函数只做一件事,并且把它做好。如果你的函数名像
process_data_and_save_to_db_and_send_email
# 不推荐
def process_and_store(data):
# 验证数据
# 转换数据格式
# 存储到数据库
pass
# 推荐
def validate_data(data):
# ...
pass
def transform_data(data):
# ...
pass
def store_to_database(data):
# ...
pass
def process_data(data):
validated = validate_data(data)
transformed = transform_data(validated)
store_to_database(transformed)清晰的命名:函数名应该像一句微型说明书,让人一眼就能看出它的作用。避免使用缩写、模糊的名称。
do_stuff()
calculate_total_price
fetch_user_profile
文档字符串 (Docstrings) 和类型提示 (Type Hints):
def calculate_discount(price: float, discount_rate: float) -> float:
"""
计算商品折扣后的价格。
Args:
price: 商品原价。
discount_rate: 折扣率 (例如 0.1 代表 10% 折扣)。
Returns:
折扣后的最终价格。
"""
if not (0 <= discount_rate <= 1):
raise ValueError("折扣率必须在 0 到 1 之间。")
return price * (1 - discount_rate)避免副作用 (Side Effects):一个“纯”函数(pure function)只依赖于它的输入参数,并且只通过返回值影响外部。它不修改全局变量,不直接进行I/O操作(比如打印、写入文件),这让函数更容易测试和理解。当然,在实际应用中,完全避免副作用是不可能的,但尽量将副作用限制在特定的函数中。
错误处理:预料到函数可能遇到的问题,并优雅地处理它们。这包括使用
try-except
ValueError
模块化设计:当项目变大时,把相关的函数组织到不同的模块(
.py
参数的合理性:如果一个函数需要七八个甚至更多的参数,那它很可能承担了过多的职责,或者它的参数设计不够合理。考虑将相关参数打包成一个字典或一个类实例。
编写可复用且易于维护的函数,是一个持续学习和实践的过程。它需要我们不断反思和优化自己的代码风格。
return
return
return
返回结果:这是最主要的作用。函数执行完任务后,将处理结果传递给调用者。没有
return
def multiply(x, y):
return x * y
product = multiply(4, 5) # product 接收到 20终止函数执行:一旦
return
def check_age(age):
if age < 0:
print("年龄不能是负数!")
return # 提前退出
print(f"你的年龄是 {age}。")
check_age(-5) # 只会打印错误信息
check_age(20) # 会打印年龄返回多个值:Python允许一个
return
def get_user_info():
name = "Alice"
age = 30
city = "New York"
return name, age, city # 实际上返回 ('Alice', 30, 'New York')
user_name, user_age, user_city = get_user_info()
print(f"姓名: {user_name}, 年龄: {user_age}, 城市: {user_city}")这种“多值返回”的特性,我个人觉得非常方便,省去了创建临时数据结构来封装结果的麻烦。
常见的陷阱和注意事项:
隐式None
return
return
None
None
def print_message(msg):
print(msg) # 没有 return 语句
result = print_message("Hello")
print(f"函数返回的值是: {result}") # 输出:函数返回的值是: None经验之谈:当函数的主要目的是执行某个操作(比如打印、修改外部状态)而不是计算并返回一个值时,让它隐式返回
None
return
return
print
return
def add_and_print(a, b):
print(a + b) # 打印结果,但不返回
def add_and_return(a, b):
return a + b # 返回结果,但不打印
val_printed = add_and_print(2, 3) # 控制台输出 5
print(f"add_and_print的返回值: {val_printed}") # 输出:add_and_print的返回值: None
val_returned = add_and_return(2, 3) # 控制台没有输出
print(f"add_and_return的返回值: {val_returned}") # 输出:add_and_return的返回值: 5如果你需要对函数的结果进行进一步处理或赋值,一定要使用
return
忘记处理None
None
None
TypeError
AttributeError
def find_item(items, key):
if key in items:
return items[key]
# else: 没有 return,隐式返回 None
my_dict = {"apple": 1}
value = find_item(my_dict, "apple")
print(value * 2) # 正常运行,输出 2
value = find_item(my_dict, "banana")
# print(value * 2) # 错误:TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
# 正确做法:
value = find_item(my_dict, "banana")
if value is not None:
print(value * 2)
else:
print("未找到该项。")养成在调用函数后检查其返回值的习惯,特别是当函数有条件地返回或可能返回
None
在循环或条件语句中的return
return
def find_first_even(numbers):
for num in numbers:
if num % 2 == 0:
return num # 找到第一个偶数就立即返回
return None # 如果没有找到偶数,返回 None
print(find_first_even([1, 3, 5, 2, 4])) # 输出 2
print(find_first_even([1, 3, 5])) # 输出 None掌握
return
以上就是Python中函数如何定义 Python中函数定义详解的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号