网站首页 > 基础教程 正文
函数是Python编程的核心构建块,掌握高级函数技巧可以显著提升代码质量和开发效率。以下是Python函数编程的进阶技巧:
1. 函数参数高级用法
1.1 灵活的参数处理
# 位置参数、默认参数、可变参数
def flexible_func(a, b=2, *args, **kwargs):
print(f"a={a}, b={b}, args={args}, kwargs={kwargs}")
flexible_func(1) # a=1, b=2, args=(), kwargs={}
flexible_func(1, 3, 4, 5, x=6, y=7) # a=1, b=3, args=(4, 5), kwargs={'x':6, 'y':7}
1.2 仅关键字参数(Python 3+)
def kw_only_arg(*, name, age):
print(f"{name} is {age} years old")
kw_only_arg(name="Alice", age=25) # 正确
# kw_only_arg("Alice", 25) # 错误,必须使用关键字参数
1.3 参数类型提示(Python 3.5+)
from typing import Optional, List, Union
def type_hinted_func(
name: str,
age: int = 18,
hobbies: Optional[List[str]] = None
) -> Union[str, None]:
"""函数带有类型注解"""
if hobbies is None:
hobbies = []
if age >= 18:
return f"{name} likes {', '.join(hobbies)}"
return None
2. 函数式编程技巧
2.1 Lambda函数
# 简单lambda
square = lambda x: x ** 2
# 在sorted中使用
users = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]
sorted_users = sorted(users, key=lambda u: u['age'])
2.2 map/filter/reduce
from functools import reduce
numbers = [1, 2, 3, 4, 5]
# map应用函数
squares = list(map(lambda x: x**2, numbers))
# filter筛选元素
evens = list(filter(lambda x: x % 2 == 0, numbers))
# reduce归约计算
sum_total = reduce(lambda x, y: x + y, numbers)
2.3 偏函数(Partial)
from functools import partial
def power(base, exponent):
return base ** exponent
# 创建固定exponent为2的新函数
square = partial(power, exponent=2)
print(square(5)) # 25
3. 装饰器高级用法
3.1 带参数的装饰器
def repeat(num_times):
def decorator_repeat(func):
def wrapper(*args, **kwargs):
for _ in range(num_times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator_repeat
@repeat(num_times=3)
def greet(name):
print(f"Hello {name}")
greet("Alice") # 打印3次
3.2 类装饰器
class CountCalls:
def __init__(self, func):
self.func = func
self.num_calls = 0
def __call__(self, *args, **kwargs):
self.num_calls += 1
print(f"Call {self.num_calls} of {self.func.__name__}")
return self.func(*args, **kwargs)
@CountCalls
def say_hello():
print("Hello!")
say_hello() # 记录调用次数
3.3 多个装饰器叠加
def decorator1(func):
def wrapper():
print("Decorator 1 before")
func()
print("Decorator 1 after")
return wrapper
def decorator2(func):
def wrapper():
print("Decorator 2 before")
func()
print("Decorator 2 after")
return wrapper
@decorator1
@decorator2
def my_func():
print("Original function")
# 执行顺序:decorator1 -> decorator2 -> my_func
4. 生成器与协程
4.1 生成器函数
def countdown(n):
print("Starting countdown")
while n > 0:
yield n
n -= 1
print("Blast off!")
for num in countdown(5):
print(num)
4.2 协程与yield
def coroutine_example():
print("Coroutine started")
while True:
x = yield
print(f"Received: {x}")
coro = coroutine_example()
next(coro) # 启动协程
coro.send(10) # 发送值
coro.send(20)
4.3 yield from (Python 3.3+)
def generator1():
yield from range(5)
yield from 'abc'
list(generator1()) # [0,1,2,3,4,'a','b','c']
5. 闭包与作用域
5.1 闭包函数
def make_multiplier(factor):
def multiplier(x):
return x * factor
return multiplier
times2 = make_multiplier(2)
times5 = make_multiplier(5)
print(times2(4)) # 8
print(times5(4)) # 20
5.2 nonlocal关键字
def counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
c = counter()
print(c(), c(), c()) # 1, 2, 3
6. 动态函数操作
6.1 动态创建函数
def create_function(name):
def new_function():
print(f"I am {name}")
return new_function
func1 = create_function("Alice")
func2 = create_function("Bob")
func1() # I am Alice
func2() # I am Bob
6.2 函数属性
7. 函数缓存与优化
7.1 使用lru_cache
from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
7.2 单分派泛函数
from functools import singledispatch
@singledispatch
def process(data):
print("Processing generic data")
@process.register(str)
def _(text):
print(f"Processing text: {text}")
@process.register(int)
def _(number):
print(f"Processing number: {number*2}")
process("hello") # Processing text: hello
process(10) # Processing number: 20
8. 上下文管理器
8.1 使用生成器实现
from contextlib import contextmanager
@contextmanager
def managed_file(filename, mode):
try:
f = open(filename, mode)
yield f
finally:
f.close()
with managed_file('test.txt', 'w') as f:
f.write('Hello')
8.2 多个上下文管理器
with open('input.txt') as f_in, open('output.txt', 'w') as f_out:
for line in f_in:
f_out.write(line.upper())
9. 函数签名与内省
9.1 获取函数签名
from inspect import signature
def func(a, b=2, *args, **kwargs):
pass
sig = signature(func)
print(str(sig)) # (a, b=2, *args, **kwargs)
9.2 参数绑定
bound_args = sig.bind(1, 2, 3, x=4)
print(bound_args.arguments) # {'a':1, 'b':2, 'args':(3,), 'kwargs':{'x':4}}
10. 异步函数(Python 3.5+)
10.1 基本异步函数
import asyncio
async def fetch_data():
print("Start fetching")
await asyncio.sleep(2)
print("Done fetching")
return {'data': 1}
async def main():
result = await fetch_data()
print(result)
asyncio.run(main())
10.2 多个协程并行
async def main():
task1 = asyncio.create_task(fetch_data())
task2 = asyncio.create_task(fetch_data())
await task1
await task2
这些函数进阶技巧可以帮助您编写更灵活、更强大的Python代码。掌握这些概念后,您将能够更好地利用Python的函数式编程特性,构建更模块化、更高效的应用程序。
猜你喜欢
- 2025-06-15 PY函数知识点及实例代码(python函数代码大全)
- 2025-06-15 学好了Python,我们可以实现很多算法了
- 2025-06-15 Python 函数式编程的 8 大核心技巧,不允许你还不会
- 2025-06-15 python的高阶函数是什么,有哪些高阶函数
- 2025-06-15 PY基础函数、自定义函数与高级函数
- 2025-06-15 python编程中列表常见的9大问题,你知道吗?
- 2025-06-15 三种不同方式,教你详细解析python反转列表(建议收藏)
- 2025-06-15 新手必看!30 个 Python 核心函数详解,手把手教你玩转编程
- 2025-06-15 Python入门到脱坑经典案例—列表排序
- 2025-06-15 零基础入门 Python 内置函数:从基础到进阶的实用指南
- 最近发表
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- queryselectorall (63)
- location.search (79)
- bootstrap教程 (74)
- deletesql (62)
- linuxgzip (68)
- 字符串连接 (73)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)