Python函数定义与调用
函数是组织代码的基本单元,通过 def 关键字定义,实现代码复用与逻辑封装。
函数定义
基本语法
Python
def function_name(parameters):
"文档字符串(可选)"
# 函数体
return result
无参数函数
Python
def greet():
print("Hello, World!")
greet() # Hello, World!
带参数函数
Python
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Hello, Alice!
参数传递机制
值传递 vs 引用传递
Python 采用"对象引用传递",效果取决于对象类型。
Python
# 不可变对象(如数字、字符串)- 类似值传递
def modify_number(n):
n = n + 1
return n
x = 10
modify_number(x)
print(x) # 10,原值不变
# 可变对象(如列表)- 类似引用传递
def modify_list(lst):
lst.append(4)
my_list = [1, 2, 3]
modify_list(my_list)
print(my_list) # [1, 2, 3, 4],原列表被修改
避免修改可变默认参数
Python
# 错误示例
def add_item(item, items=[]):
items.append(item)
return items
print(add_item(1)) # [1]
print(add_item(2)) # [1, 2] - 意外保留!
# 正确做法
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
返回值
单返回值
Python
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 8
多返回值(实际返回元组)
Python
def get_info():
name = "Alice"
age = 25
return name, age
n, a = get_info() # 元组解包
print(n, a) # Alice 25
# 等价于
info = get_info()
print(info) # ('Alice', 25)
无返回值
Python
def greet(name):
print(f"Hello, {name}!")
result = greet("Bob")
print(result) # None(隐式返回)
函数调用
位置参数调用
Python
def power(base, exponent):
return base ** exponent
print(power(2, 3)) # 8
关键字参数调用
Python
def power(base, exponent):
return base ** exponent
print(power(base=2, exponent=3)) # 8
print(power(exponent=3, base=2)) # 8,顺序无关
混合调用
Python
def describe(name, age, city):
return f"{name}, {age} years old, from {city}"
# 位置参数必须在关键字参数之前
print(describe("Alice", 25, city="Beijing")) # 正确
# print(describe(name="Alice", 25)) # 语法错误
函数文档
docstring 规范
Python
def calculate_area(length, width):
"
计算矩形面积。
Args:
length: 长度
width: 宽度
Returns:
矩形面积
"
return length * width
print(calculate_area.__doc__)
要点总结
- 使用
def关键字定义函数 - 参数传递按对象引用,可变对象会被修改
- 可通过元组返回多个值
- 无 return 语句返回 None
- 文档字符串描述函数功能
📝 发现内容有误?点击此处直接编辑