你可能不知道的实用 Python 功能(python有哪些用)
off999 2025-06-15 18:36 4 浏览 0 评论
1. 超越文件处理的内容管理器
大多数开发人员都熟悉使用 with 语句进行文件操作:
with open('file.txt', 'r') as file:
content = file.read()
# File is automatically closed after this block
但是, 内容管理器 可以做更多更多。它们是所有类型资源管理的完美选择:
from contextlib import contextmanager
import time
@contextmanager
def timer():
"""Measure execution time of a code block."""
start = time.time()
try:
yield # This is where the code within the 'with' block executes
finally:
end = time.time()
print(f"Elapsed time: {end - start:.4f} seconds")
# Usage
with timer():
# Some time-consuming operation
result = sum(range(10_000_000))
contextlib 模块还提供了方便的工具,比如 suppress 用于抑制特定的异常 :
from contextlib import suppress
# Instead of:
try:
os.remove('temp_file.txt')
except FileNotFoundError:
pass
# You can write:
with suppress(FileNotFoundError):
os.remove('temp_file.txt')
2. 部分函数
functools.partial (?) 函数允许你创建带有预填充参数的新函数 :
from functools import partial
# Instead of writing a new function
def power_of_two(x):
return pow(x, 2)
# You can use partial
power_of_two = partial(pow, exp=2)
# Create a base-2 logarithm function
import math
log2 = partial(math.log, base=2)
print(log2(8)) # Outputs: 3.0
这对于回调函数或在处理 高阶函数 时特别有用。
3. 解构泛化
解包运算符 * 和 ** 比我们大多数人都意识到的要更通用:
# Merging dictionaries (Python 3.5+)
defaults = {"colour": "red", "size": "medium"}
user_settings = {"size": "large", "mode": "advanced"}
settings = {**defaults, **user_settings}
print(settings) # {'colour': 'red', 'size': 'large', 'mode': 'advanced'}
# Extended unpacking (Python 3.0+)
first, *middle, last = [1, 2, 3, 4, 5]
print(middle) # [2, 3, 4]
# Unpacking in function calls
def tag(name, **attributes):
attr_str = ' '.join(f'{k}="{v}"' for k, v in attributes.items())
return f'<{name} {attr_str}>'
props = {"class": "button", "id": "submit-btn", "disabled": True}
print(tag("button", **props)) # <button class="button" id="submit-btn" disabled="True">
4. 省略号(...)的意外用途
省略号字面量不只是用于类型提示:
# As a placeholder for future code
def function_to_implement_later():
... # More explicit than 'pass'
# In multidimensional NumPy slicing
import numpy as np
array = np.random.rand(4, 4, 4)
# Select the middle column from all rows in all matrices
middle_column = array[:, 1, ...]
5. 函数属性
Python 函数是对象,可以有属性 :
def process_data(data, verbose=False):
"""Process the given data."""
if verbose or process_data.always_verbose:
print("Processing data...")
# Processing logic here
return data
# Add an attribute to the function
process_data.always_verbose = False
# Later in your code
process_data.always_verbose = True # Enable verbose mode globally
这可以是在某些情况下作为全局变量的一个酷替代方案。
6. 自定义排序键使用key=参数
排序函数中的 key 参数比大多数人意识到的要强大得多:
# Sort strings by length
words = ["apple", "pear", "banana", "strawberry", "fig"]
sorted_by_length = sorted(words, key=len)
print(sorted_by_length) # ['fig', 'pear', 'apple', 'banana', 'strawberry']
# Sort complex objects
from operator import attrgetter, itemgetter
# For a list of dictionaries
users = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35}
]
sorted_users = sorted(users, key=itemgetter("age"))
# For a list of objects
from collections import namedtuple
Person = namedtuple("Person", ["name", "age"])
people = [Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35)]
sorted_people = sorted(people, key=attrgetter("age"))
7. 默认字典和计数器集合
collections 模块包含可以替代常见模式的数据结构 :
from collections import defaultdict, Counter
# Instead of:
word_count = {}
for word in text.split():
if word not in word_count:
word_count[word] = 0
word_count[word] += 1
# You can use:
word_count = defaultdict(int)
for word in text.split():
word_count[word] += 1
# Or even simpler:
word_count = Counter(text.split())
print(word_count.most_common(5)) # Shows the 5 most common words
8. 枚举类型用于更好的常量
枚举模块有助于定义有意义的常量:
from enum import Enum, auto
class Status(Enum):
PENDING = auto()
RUNNING = auto()
COMPLETED = auto()
FAILED = auto()
def process_job(job, status):
if status == Status.RUNNING:
print(f"Job {job} is still running")
elif status == Status.COMPLETED:
print(f"Job {job} completed successfully")
# ...
# So much more readable than numeric constants
current_status = Status.RUNNING
process_job("backup", current_status)
9. 数据类用于更简洁的代码
Python 3.7 引入了 数据类 (通过 PEP-557),它们减少了主要用于存储数据的类中的样板代码:
from dataclasses import dataclass, field
from typing import List
@dataclass
class Student:
name: str
student_id: int
courses: List[str] = field(default_factory=list)
active: bool = True
def enroll(self, course):
self.courses.append(course)
# No need to write __init__, __repr__, __eq__, etc.
student = Student("Jane Smith", 12345)
student.enroll("Computer Science 101")
print(student) # Student(name='Jane Smith', student_id=12345, courses=['Computer Science 101'], active=True)
10. 使用__slots__提高内存效率
对于具有固定属性集的类,__slots__ 可以显著减少内存使用:
class RegularPoint:
def __init__(self, x, y):
self.x = x
self.y = y
class MemoryEfficientPoint:
__slots__ = ['x', 'y']
def __init__(self, x, y):
self.x = x
self.y = y
# The __slots__ version uses significantly less memory when many instances are created
import sys
regular = RegularPoint(3, 4)
efficient = MemoryEfficientPoint(3, 4)
print(sys.getsizeof(regular)) # Typically larger
print(sys.getsizeof(efficient)) # Typically smaller
11. f 字符串调试(Python 3.8+)
在 Python 3.8 中,f 字符串增加了一个方便的调试功能: 已添加
x = 10
y = 20
print(f"{x=}, {y=}, {x+y=}")
# Outputs: x=10, y=20, x+y=30
通过显示变量名及其值,在调试时节省时间。
12. pathlib 用于现代文件操作
pathlib 模块为文件系统路径提供了面向对象的方法:
from pathlib import Path
# Create paths
data_dir = Path("data")
file_path = data_dir / "output.txt" # Path joining with / operator
# Create directory if it doesn't exist
data_dir.mkdir(exist_ok=True)
# Write to a file
file_path.write_text("Hello, world!")
# Read from a file
content = file_path.read_text()
# Iterate over files in a directory
for python_file in data_dir.glob("*.py"):
print(f"Found Python file: {python_file.name}")
。
相关推荐
- 面试官:来,讲一下枚举类型在开发时中实际应用场景!
-
一.基本介绍枚举是JDK1.5新增的数据类型,使用枚举我们可以很好的描述一些特定的业务场景,比如一年中的春、夏、秋、冬,还有每周的周一到周天,还有各种颜色,以及可以用它来描述一些状态信息,比如错...
- 一日一技:11个基本Python技巧和窍门
-
1.两个数字的交换.x,y=10,20print(x,y)x,y=y,xprint(x,y)输出:102020102.Python字符串取反a="Ge...
- Python Enum 技巧,让代码更简洁、更安全、更易维护
-
如果你是一名Python开发人员,你很可能使用过enum.Enum来创建可读性和可维护性代码。今天发现一个强大的技巧,可以让Enum的境界更进一层,这个技巧不仅能提高可读性,还能以最小的代价增...
- Python元组编程指导教程(python元组的概念)
-
1.元组基础概念1.1什么是元组元组(Tuple)是Python中一种不可变的序列类型,用于存储多个有序的元素。元组与列表(list)类似,但元组一旦创建就不能修改(不可变),这使得元组在某些场景...
- 你可能不知道的实用 Python 功能(python有哪些用)
-
1.超越文件处理的内容管理器大多数开发人员都熟悉使用with语句进行文件操作:withopen('file.txt','r')asfile:co...
- Python 2至3.13新特性总结(python 3.10新特性)
-
以下是Python2到Python3.13的主要新特性总结,按版本分类整理:Python2到Python3的重大变化Python3是一个不向后兼容的版本,主要改进包括:pri...
- Python中for循环访问索引值的方法
-
技术背景在Python编程中,我们经常需要在循环中访问元素的索引值。例如,在处理列表、元组等可迭代对象时,除了要获取元素本身,还需要知道元素的位置。Python提供了多种方式来实现这一需求,下面将详细...
- Python enumerate核心应用解析:索引遍历的高效实践方案
-
喜欢的条友记得关注、点赞、转发、收藏,你们的支持就是我最大的动力源泉。根据GitHub代码分析统计,使用enumerate替代range(len())写法可减少38%的索引错误概率。本文通过12个生产...
- Python入门到脱坑经典案例—列表去重
-
列表去重是Python编程中常见的操作,下面我将介绍多种实现列表去重的方法,从基础到进阶,帮助初学者全面掌握这一技能。方法一:使用集合(set)去重(最简单)pythondefremove_dupl...
- Python枚举类工程实践:常量管理的标准化解决方案
-
本文通过7个生产案例,系统解析枚举类在工程实践中的应用,覆盖状态管理、配置选项、错误代码等场景,适用于Web服务开发、自动化测试及系统集成领域。一、基础概念与语法演进1.1传统常量与枚举类对比#传...
- 让Python枚举更强大!教你玩转Enum扩展
-
为什么你需要关注Enum?在日常开发中,你是否经常遇到这样的代码?ifstatus==1:print("开始处理")elifstatus==2:pri...
- Python枚举(Enum)技巧,你值得了解
-
枚举(Enum)提供了更清晰、结构化的方式来定义常量。通过为枚举添加行为、自动分配值和存储额外数据,可以提升代码的可读性、可维护性,并与数据库结合使用时,使用字符串代替数字能简化调试和查询。Pytho...
- 78行Python代码帮你复现微信撤回消息!
-
来源:悟空智能科技本文约700字,建议阅读5分钟。本文基于python的微信开源库itchat,教你如何收集私聊撤回的信息。[导读]Python曾经对我说:"时日不多,赶紧用Python"。于是看...
- 登录人人都是产品经理即可获得以下权益
-
文章介绍如何利用Cursor自动开发Playwright网页自动化脚本,实现从选题、写文、生图的全流程自动化,并将其打包成API供工作流调用,提高工作效率。虽然我前面文章介绍了很多AI工作流,但它们...
- Python常用小知识-第二弹(python常用方法总结)
-
一、Python中使用JsonPath提取字典中的值JsonPath是解析Json字符串用的,如果有一个多层嵌套的复杂字典,想要根据key和下标来批量提取value,这是比较困难的,使用jsonpat...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python自定义函数 (53)
- python进度条 (67)
- python吧 (67)
- python字典遍历 (54)
- python的for循环 (65)
- python格式化字符串 (61)
- python串口编程 (60)
- python读取文件夹下所有文件 (59)
- java调用python脚本 (56)
- python操作mysql数据库 (66)
- python字典增加键值对 (53)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python人脸识别 (54)
- python多态 (60)
- python命令行参数 (53)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)