网站首页 > 技术文章 正文
函数是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-03 这3个高级Python函数,不能再被你忽略了
- 2025-06-03 python组合函数不允许你还不会的 10 个高效技巧
- 2025-06-03 Python内置函数range(python内置函数大全表)
- 2025-06-03 你不得不知道的10个最危险的Python函数
- 2025-06-03 告别重复,打造你的代码工具箱:Python函数深度解析
- 2025-06-03 30天学会Python编程:6. Python函数编程
- 2025-06-03 python入门到脱坑 函数—函数的调用
- 2025-06-03 Python内置函数指南(python内置函数有哪些)
- 2025-06-03 PYTHON函数参数详解(python函数参数的类型)
- 2025-06-03 Python程序员都应该学习掌握的的25个最基本内置函数
- 263℃Python短文,Python中的嵌套条件语句(六)
- 262℃python笔记:for循环嵌套。end=""的作用,图形打印
- 261℃PythonNet:实现Python与.Net代码相互调用!
- 256℃Python实现字符串小写转大写并写入文件
- 255℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 115℃原来2025是完美的平方年,一起探索六种平方的算吧
- 96℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 88℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)