一文读懂Python函数:基础、进阶与最佳实践

15 阅读2分钟

一、什么是函数?

函数(Function)是组织好的、可重复使用的、用来实现单一或相关联功能的代码段。它能让代码更简洁、可维护性更强。

1.1 为什么要用函数?

  • 复用代码:避免重复劳动
  • 提高可读性:让代码结构更清晰
  • 便于维护:修改时只需改一处

二、Python函数的基础用法

2.1 定义和调用函数

def greet():
    print("Hello, Python!")
    
greet()  # 输出:Hello, Python!

2.2 带参数的函数

def greet(name):
    print(f"Hello, {name}!")
    
greet("Alice")  # 输出:Hello, Alice!

2.3 返回值

def add(a, b):
    return a + b

result = add(3, 5)
print(result)  # 输出:8

三、进阶用法

3.1 默认参数

def greet(name="World"):
    print(f"Hello, {name}!")

greet()         # 输出:Hello, World!
greet("Bob")    # 输出:Hello, Bob!

3.2 关键字参数

def introduce(name, age):
    print(f"My name is {name}, and I'm {age} years old.")

introduce(age=25, name="Alice")

3.3 可变参数

  • *args:接收任意数量的位置参数
  • **kwargs:接收任意数量的关键字参数
def demo(*args, **kwargs):
    print("args:", args)
    print("kwargs:", kwargs)

demo(1, 2, 3, a=4, b=5)
# 输出:
# args: (1, 2, 3)
# kwargs: {'a': 4, 'b': 5}

四、函数的高级特性

4.1 匿名函数(lambda表达式)

square = lambda x: x * x
print(square(5))  # 输出:25

4.2 函数作为参数传递

def apply(func, value):
    return func(value)

print(apply(lambda x: x + 1, 10))  # 输出:11

4.3 闭包(Closure)

def outer(x):
    def inner(y):
        return x + y
    return inner

add_five = outer(5)
print(add_five(10))  # 输出:15

4.4 装饰器(Decorator)

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()

五、最佳实践与常见误区

5.1 函数注释与类型提示

def add(a: int, b: int) -> int:
    """
    两数相加
    """
    return a + b

5.2 函数返回多个值其实是元组

def foo():
    return 1, 2

result = foo()
print(result)      # (1, 2)
a, b = foo()
print(a, b)        # 1 2

5.3 参数解包顺序错误

def func(a, b, c):
    print(a, b, c)

args = (1, 2, 3)
func(*args)  # 正确

kwargs = {'a': 1, 'b': 2, 'c': 3}
func(**kwargs)  # 正确

误区:*args和**kwargs不能乱用,顺序和名称要对应。


如果你觉得这篇文章有用,记得点赞、关注、收藏,学Python更轻松!!