Python 函数进阶的10大技巧,不允许你还不会
off999 2025-07-08 22:07 18 浏览 0 评论
函数是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的函数式编程特性,构建更模块化、更高效的应用程序。
相关推荐
- 大文件传不动?WinRAR/7-Zip 入门到高手,这 5 个技巧让你效率翻倍
-
“这200张照片怎么传给女儿?微信发不了,邮箱附件又超限……”62岁的张阿姨对着电脑犯愁时,儿子只用了3分钟就把照片压缩成一个文件,还教她:“以后用压缩软件,比打包行李还方便!”职场人更懂这...
- 电脑解压缩软件推荐——7-Zip:免费、高效、简洁的文件管理神器
-
在日常工作中,我们经常需要处理压缩文件。无论是下载软件包、接收文件,还是存储大量数据,压缩和解压缩文件都成为了我们日常操作的一部分。而说到压缩解压软件,7-Zip绝对是一个不可忽视的名字。今天,我就来...
- 设置了加密密码zip文件要如何打开?这几个方法可以试试~
-
Zip是一种常见的压缩格式文件,文件还可以设置密码保护。那设置了密码的Zip文件要如何打开呢?不清楚的小伙伴一起来看看吧。当我们知道密码想要打开带密码的Zip文件,我们需要用到适用于Zip格式的解压缩...
- 大文件想要传输成功,怎么把ZIP文件分卷压缩
-
不知道各位小伙伴有没有这样的烦恼,发送很大很大的压缩包会受到限制,为此,想要在压缩过程中将文件拆分为几个压缩包并且同时为所有压缩包设置加密应该如何设置?方法一:使用7-Zip免费且强大的文件管理工具7...
- 高效处理 RAR 分卷压缩包:合并解压操作全攻略
-
在文件传输和存储过程中,当遇到大文件时,我们常常会使用分卷压缩的方式将其拆分成多个较小的压缩包,方便存储和传输。RAR作为一种常见的压缩格式,分卷压缩包的使用频率也很高。但很多人在拿到RAR分卷...
- 2个方法教你如何删除ZIP压缩包密码
-
zip压缩包设置了加密密码,每次解压文件都需要输入密码才能够顺利解压出文件,当压缩包文件不再需要加密的时候,大家肯定想删除压缩包密码,或是忘记了压缩包密码,想要通过删除操作将压缩包密码删除,就能够顺利...
- 速转!漏洞预警丨压缩软件Winrar目录穿越漏洞
-
WinRAR是一款功能强大的压缩包管理器,它是档案工具RAR在Windows环境下的图形界面。该软件可用于备份数据,缩减电子邮件附件的大小,解压缩从Internet上下载的RAR、ZIP及其它类...
- 文件解压方法和工具分享_文件解压工具下载
-
压缩文件减少文件大小,降低文件失效的概率,总得来说好处很多。所以很多文件我们下载下来都是压缩软件,很多小伙伴不知道怎么解压,或者不知道什么工具更好,所以今天做了文件解压方法和工具的分享给大家。一、解压...
- [python]《Python编程快速上手:让繁琐工作自动化》学习笔记3
-
1.组织文件笔记(第9章)(代码下载)1.1文件与文件路径通过importshutil调用shutil模块操作目录,shutil模块能够在Python程序中实现文件复制、移动、改名和删除;同时...
- Python内置tarfile模块:读写 tar 归档文件详解
-
一、学习目标1.1学习目标掌握Python内置模块tarfile的核心功能,包括:理解tar归档文件的原理与常见压缩格式(gzip/bz2/lzma)掌握tar文件的读写操作(创建、解压、查看、过滤...
- 使用python展开tar包_python拓展
-
类Unix的系统,打包文件经常使用的就是tar包,结合zip工具,可以方便的打包并解压。在python的标准库里面有tarfile库,可以方便实现生成了展开tar包。使用这个库最大的好处,可能就在于不...
- 银狐钓鱼再升级:白文件脚本化实现GO语言后门持久驻留
-
近期,火绒威胁情报中心监测到一批相对更为活跃的“银狐”系列变种木马。火绒安全工程师第一时间获取样本并进行分析。分析发现,该样本通过阿里云存储桶下发恶意文件,采用AppDomainManager进行白利...
- ZIP文件怎么打开?2个简单方法教你轻松搞定!
-
在日常工作和生活中,我们经常会遇到各种压缩文件,其中最常见的格式之一就是ZIP。ZIP文件通过压缩数据来减少文件大小,方便我们进行存储和传输。然而,对于初学者来说,如何打开ZIP文件可能会成为一个小小...
- Ubuntu—解压多个zip压缩文件.zip .z01 .z02
-
方法将所有zip文件放在同一目录中:zip_file.z01,zip_file.z02,zip_file.z03,...,zip_file.zip。在Zip3.0版本及以上,使用下列命令:将所有zi...
- 如何使用7-Zip对文件进行加密压缩
-
7-Zip是一款开源的文件归档工具,支持多种压缩格式,并提供了对压缩文件进行加密的功能。使用7-Zip可以轻松创建和解压.7z、.zip等格式的压缩文件,并且可以通过设置密码来保护压缩包中的...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (77)
- python封装 (57)
- python写入txt (66)
- python读取文件夹下所有文件 (59)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)