函数是Python编程中最重要的构建块之一,本文将用通俗易懂的方式全面讲解Python函数的各种知识点,包括基本概念、参数传递、作用域、装饰器、属性和方法等。
函数是一段可重复使用的代码块,它接受输入(参数),执行特定任务,然后返回结果。
# 定义一个简单的函数
def greet(name):
"""这是一个问候函数"""
return f"Hello, {name}!"
# 调用函数
print(greet("Alice")) # 输出: Hello, Alice!
组成部分 | 说明 | 示例 |
---|---|---|
def 关键字 |
用于定义函数 | def my_function(): |
函数名 | 函数的标识符 | greet , calculate_sum |
参数 | 函数接受的输入 | (name, age) |
冒号 : |
表示函数体开始 | def func(): 后面的 : |
函数体 | 函数执行的代码块 | 缩进的代码部分 |
返回值 | 函数返回的结果 | return result |
文档字符串 | 函数的说明文档 | """这是函数的说明""" |
参数类型 | 定义方式 | 调用方式 | 特点 |
---|---|---|---|
位置参数 | def func(a, b): |
func(1, 2) |
按位置顺序传递 |
关键字参数 | def func(a, b): |
func(a=1, b=2) |
明确指定参数名 |
默认参数 | def func(a=1, b=2): |
func() 或 func(3) |
参数有默认值 |
可变位置参数 | def func(*args): |
func(1, 2, 3) |
接收任意数量位置参数 |
可变关键字参数 | def func(**kwargs): |
func(a=1, b=2) |
接收任意数量关键字参数 |
# 位置参数和关键字参数
def describe_pet(animal_type, pet_name):
print(f"I have a {animal_type} named {pet_name}.")
describe_pet('hamster', 'Harry') # 位置参数
describe_pet(pet_name='Harry', animal_type='hamster') # 关键字参数
# 默认参数
def describe_pet(pet_name, animal_type='dog'):
print(f"I have a {animal_type} named {pet_name}.")
describe_pet('Willie') # 使用默认的animal_type
describe_pet('Harry', 'hamster') # 覆盖默认值
# 可变参数
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')
# 可变关键字参数
def build_profile(**user_info):
profile = {}
for key, value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile(name='Alice', age=25, occupation='Engineer')
print(user_profile)
Python中有四种作用域,查找顺序如下:
局部(Local) → 嵌套(Enclosing) → 全局(Global) → 内置(Built-in) → 报错
x = 'global x' # 全局变量
def outer():
x = 'outer x' # 嵌套作用域变量
def inner():
x = 'inner x' # 局部变量
print(x) # 输出: inner x
inner()
print(x) # 输出: outer x
outer()
print(x) # 输出: global x
x = 10
def modify_global():
global x # 声明使用全局变量
x = 20
modify_global()
print(x) # 输出: 20
def outer():
x = 10
def inner():
nonlocal x # 声明使用嵌套作用域变量
x = 20
inner()
print(x) # 输出: 20
outer()
Python函数对象有许多内置属性:
属性 | 描述 | 示例 |
---|---|---|
__name__ |
函数名 | func.__name__ |
__doc__ |
文档字符串 | func.__doc__ |
__module__ |
定义函数的模块名 | func.__module__ |
__defaults__ |
默认参数的元组 | func.__defaults__ |
__code__ |
包含编译代码的对象 | func.__code__.co_varnames |
def example(a, b=1, *args, **kwargs):
"""这是一个示例函数"""
pass
print(example.__name__) # 输出: example
print(example.__doc__) # 输出: 这是一个示例函数
print(example.__defaults__) # 输出: (1,)
函数也是对象,可以拥有自己的属性和方法:
def my_func():
pass
# 添加自定义属性
my_func.custom_attr = "This is a custom attribute"
print(my_func.custom_attr) # 输出: This is a custom attribute
# 函数也是对象,可以存储在数据结构中
functions = [my_func, print, len]
for func in functions:
print(func.__name__)
def shout(text):
return text.upper()
def whisper(text):
return text.lower()
def greet(func):
greeting = func("Hello, Python!")
print(greeting)
greet(shout) # 输出: HELLO, PYTHON!
greet(whisper) # 输出: hello, python!
def outer_func(x):
def inner_func(y):
return x + y
return inner_func
closure = outer_func(10)
print(closure(5)) # 输出: 15
def my_decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
# 输出:
# Before function call
# Hello!
# After function call
# 普通函数
def square(x):
return x ** 2
# lambda等效
square = lambda x: x ** 2
print(square(5)) # 输出: 25
# 常用于排序
points = [(1, 2), (3, 1), (5, 4)]
points.sort(key=lambda point: point[1])
print(points) # 输出: [(3, 1), (1, 2), (5, 4)]
def countdown(n):
while n > 0:
yield n
n -= 1
for i in countdown(5):
print(i) # 输出: 5 4 3 2 1
def greet(name: str, age: int = 30) -> str:
return f"Hello {name}, you are {age} years old."
print(greet("Alice", 25))
print(greet.__annotations__)
# 输出: {'name': , 'age': , 'return': }
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
cube = partial(power, exponent=3)
print(square(5)) # 输出: 25
print(cube(5)) # 输出: 125
# 好的函数示例
def calculate_circle_area(radius):
"""计算圆的面积
Args:
radius (float): 圆的半径
Returns:
float: 圆的面积
"""
return 3.14159 * radius ** 2
通过本文的讲解,你应该对Python函数的各个方面有了全面的了解。从基础定义到高级特性,函数是Python编程中不可或缺的部分。掌握这些知识将帮助你编写更清晰、更高效的代码。