1. 函数基础
1.1 定义函数
在Python中,使用def
关键字来定义函数:
def greet():
"""简单的问候函数"""
print("Hello, World!")
1.2 调用函数
定义函数后,可以通过函数名加括号来调用:
greet() # 输出: Hello, World!
1.3 函数的文档字符串
函数的第一行字符串称为文档字符串(docstring),用于描述函数的功能:
def greet():
"""这是一个简单的问候函数"""
print("Hello, World!")
print(greet.__doc__) # 输出: 这是一个简单的问候函数
2. 函数参数
2.1 位置参数
def greet(name, greeting):
print(f"{greeting}, {name}!")
greet("Alice", "Hello") # 输出: Hello, Alice!
2.2 默认参数
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Bob") # 输出: Hello, Bob!
greet("Charlie", "Hi") # 输出: Hi, Charlie!
2.3 关键字参数
def describe_pet(pet_name, animal_type="dog"):
print(f"I have a {animal_type} named {pet_name}.")
describe_pet(pet_name="Max") # 输出: I have a dog named Max.
describe_pet(animal_type="cat", pet_name="Whiskers") # 输出: I have a cat named Whiskers.
2.4 可变参数
2.4.1 *args - 接收任意数量的位置参数
def make_pizza(*toppings):
print("Making a pizza with:")
for topping in toppings:
print(f"- {topping}")
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
2.4.2 **kwargs - 接收任意数量的关键字参数
def build_profile(first, last, **user_info):
user_info['first_name'] = first
user_info['last_name'] = last
return user_info
user_profile = build_profile('albert', 'einstein',
location='princeton',
field='physics')
print(user_profile)
3. 返回值
使用return
语句从函数返回值:
def add(a, b):
"""返回两个数的和"""
return a + b
result = add(3, 5)
print(result) # 输出: 8
4. 变量作用域
4.1 局部变量
def test_local():
x = 10 # 局部变量
print(x)
test_local() # 输出: 10
print(x) # 报错: NameError: name 'x' is not defined
4.2 全局变量
x = 20 # 全局变量
def test_global():
print(x) # 可以访问全局变量
test_global() # 输出: 20
print(x) # 输出: 20
4.3 修改全局变量
x = 20
def modify_global():
global x # 声明使用全局变量
x = 30
modify_global()
print(x) # 输出: 30
5. Lambda函数
Lambda函数是小型匿名函数:
square = lambda x: x ** 2
print(square(5)) # 输出: 25
6. 高阶函数
6.1 map()函数
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared) # 输出: [1, 4, 9, 16]
6.2 filter()函数
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # 输出: [2, 4, 6]
6.3 reduce()函数
from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product) # 输出: 24
7. 装饰器
装饰器用于修改或扩展函数的行为:
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
8. 生成器函数
使用yield
关键字创建生成器:
def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1
counter = count_up_to(5)
for num in counter:
print(num) # 输出: 1 2 3 4 5
9. 递归函数
函数调用自身:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
print(factorial(5)) # 输出: 120
10. 闭包
函数嵌套并返回内部函数:
def outer_func(x):
def inner_func(y):
return x + y
return inner_func
closure = outer_func(10)
print(closure(5)) # 输出: 15
11. 函数注解
为函数参数和返回值添加类型注解:
def greet(name: str, age: int) -> str:
return f"Hello {name}, you are {age} years old."
print(greet("Alice", 30))
12. 内置函数
Python有许多内置函数,如:
len()
,print()
,input()
max()
,min()
,sum()
sorted()
,reversed()
abs()
,round()
,pow()
type()
,isinstance()
open()
,range()
,enumerate()
zip()
,iter()
,next()
13. 最佳实践
- 函数应该只做一件事
- 保持函数简短
- 使用描述性的函数名
- 避免过多的参数
- 使用默认参数简化调用
- 为函数添加文档字符串
- 考虑使用类型注解
14. 总结
Python函数是代码重用的基本单元,掌握函数的使用对于编写清晰、模块化和可维护的代码至关重要。从简单的函数定义到高级特性如装饰器和生成器,Python提供了丰富的功能来满足各种编程需求。