在 Python 中,自定义函数除了基本的定义和调用外,还有一些高级用法,可以让函数更加灵活和强大。以下是一些自定义函数的高级用法示例:
1. 默认参数
函数定义时可以指定默认参数值,当调用函数时没有提供该参数的值时,将使用默认值。
def greet(name, greeting='Hello'): print(f"{greeting}, {name}!") greet('Alice') # 输出:Hello, Alice!
greet('Bob', 'Hi') # 输出:Hi, Bob!
2. 可变参数
使用 *args
和 **kwargs
来接收任意数量的位置参数和关键字参数。
def sum_numbers(*args): return sum(args) print(sum_numbers(1, 2, 3, 4)) # 输出:10 def complex_greet(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") complex_greet(name='Alice', age=30, country='USA')
# 输出:
# name: Alice
# age: 30
# country: USA
3. 函数注解(类型注解)
函数注解用于为函数参数和返回值提供类型信息,虽然这些信息在运行时不会强制执行,但可以帮助其他开发者理解你的代码意图,并且一些工具(如类型检查器)可以利用这些注解进行静态类型检查。
def greet(name: str, age: int) -> None: print(f"Hello, {name}. You are {age} years old.") greet('Alice', 30) # 正常运行 # greet('Alice', 'thirty') # 如果没有类型检查器,这行代码也能运行,但可能不符合预期
4. 嵌套函数
一个函数内部可以定义另一个函数,这种函数叫做嵌套函数。嵌套函数可以访问其外部函数的作用域(但不能修改外部函数的局部作用域中的变量,除非使用 nonlocal
关键字)。
def outer_function():x = 10def inner_function():print(x)inner_function()outer_function() # 输出:10
5. 闭包
闭包是一个返回函数的函数,并且这个返回的函数使用了外部函数的作用域中的变量。这样,返回的函数就“记住”了它的外部函数作用域中的变量。
def outer_function(x):def inner_function():print(x)return inner_functionclosure = outer_function(10)closure() # 输出:10
6. 装饰器
装饰器是一个函数,它接受一个函数作为参数,并返回一个新的函数。装饰器可以用于修改或增强函数的行为,例如添加日志、性能测量、权限检查等。
def decorator_function(original_function): def wrapper_function(*args, **kwargs): print("Something is happening before the function is called.") result = original_function(*args, **kwargs) print("Something is happening after the function is called.") return result return wrapper_function @decorator_function
def say_hello(name): print(f"Hello {name}!") say_hello("Alice")
# 输出:
# Something is happening before the function is called.
# Hello Alice!
# Something is happening after the function is called.
7. 偏函数(Partial Function)
使用 functools.partial
可以创建一个新的部分应用函数,该函数将原始函数的某些参数设置为默认值。
from functools import partial def greet(greeting, name): print(f"{greeting}, {name}!") greet_hello = partial(greet, greeting='Hello')
greet_hello('Alice') # 输出:Hello, Alice!