你可能不知道的实用 Python 功能(python有哪些用)
off999 2025-06-15 18:36 24 浏览 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 words8. 枚举类型用于更好的常量
枚举模块有助于定义有意义的常量:
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 smaller11. 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}")。
相关推荐
- 阿里云国际站ECS:阿里云ECS如何提高网站的访问速度?
-
TG:@yunlaoda360引言:速度即体验,速度即业务在当今数字化的世界中,网站的访问速度已成为决定用户体验、用户留存乃至业务转化率的关键因素。页面加载每延迟一秒,都可能导致用户流失和收入损失。对...
- 高流量大并发Linux TCP性能调优_linux 高并发网络编程
-
其实主要是手里面的跑openvpn服务器。因为并没有明文禁p2p(哎……想想那么多流量好像不跑点p2p也跑不完),所以造成有的时候如果有比较多人跑BT的话,会造成VPN速度急剧下降。本文所面对的情况为...
- 性能测试100集(12)性能指标资源使用率
-
在性能测试中,资源使用率是评估系统硬件效率的关键指标,主要包括以下四类:#性能测试##性能压测策略##软件测试#1.CPU使用率定义:CPU处理任务的时间占比,计算公式为1-空闲时间/总...
- Linux 服务器常见的性能调优_linux高性能服务端编程
-
一、Linux服务器性能调优第一步——先搞懂“看什么”很多人刚接触Linux性能调优时,总想着直接改配置,其实第一步该是“看清楚问题”。就像医生看病要先听诊,调优前得先知道服务器“哪里...
- Nginx性能优化实战:手把手教你提升10倍性能!
-
关注△mikechen△,十余年BAT架构经验倾囊相授!Nginx是大型架构而核心,下面我重点详解Nginx性能@mikechen文章来源:mikechen.cc1.worker_processe...
- 高并发场景下,Spring Cloud Gateway如何抗住百万QPS?
-
关注△mikechen△,十余年BAT架构经验倾囊相授!大家好,我是mikechen。高并发场景下网关作为流量的入口非常重要,下面我重点详解SpringCloudGateway如何抗住百万性能@m...
- Kubernetes 高并发处理实战(可落地案例 + 源码)
-
目标场景:对外提供HTTPAPI的微服务在短时间内收到大量请求(例如每秒数千至数万RPS),要求系统可弹性扩容、限流降级、缓存减压、稳定运行并能自动恢复。总体思路(多层防护):边缘层:云LB...
- 高并发场景下,Nginx如何扛住千万级请求?
-
Nginx是大型架构的必备中间件,下面我重点详解Nginx如何实现高并发@mikechen文章来源:mikechen.cc事件驱动模型Nginx采用事件驱动模型,这是Nginx高并发性能的基石。传统...
- Spring Boot+Vue全栈开发实战,中文版高清PDF资源
-
SpringBoot+Vue全栈开发实战,中文高清PDF资源,需要的可以私我:)SpringBoot致力于简化开发配置并为企业级开发提供一系列非业务性功能,而Vue则采用数据驱动视图的方式将程序...
- Docker-基础操作_docker基础实战教程二
-
一、镜像1、从仓库获取镜像搜索镜像:dockersearchimage_name搜索结果过滤:是否官方:dockersearch--filter="is-offical=true...
- 你有空吗?跟我一起搭个服务器好不好?
-
来人人都是产品经理【起点学院】,BAT实战派产品总监手把手系统带你学产品、学运营。昨天闲的没事的时候,随手翻了翻写过的文章,发现一个很严重的问题。就是大多数时间我都在滔滔不绝的讲理论,却很少有涉及动手...
- 部署你自己的 SaaS_saas如何部署
-
部署你自己的VPNOpenVPN——功能齐全的开源VPN解决方案。(DigitalOcean教程)dockovpn.io—无状态OpenVPNdockerized服务器,不需要持久存储。...
- Docker Compose_dockercompose安装
-
DockerCompose概述DockerCompose是一个用来定义和管理多容器应用的工具,通过一个docker-compose.yml文件,用YAML格式描述服务、网络、卷等内容,...
- 京东T7架构师推出的电子版SpringBoot,从构建小系统到架构大系统
-
前言:Java的各种开发框架发展了很多年,影响了一代又一代的程序员,现在无论是程序员,还是架构师,使用这些开发框架都面临着两方面的挑战。一方面是要快速开发出系统,这就要求使用的开发框架尽量简单,无论...
- Kubernetes (k8s) 入门学习指南_k8s kubeproxy
-
Kubernetes(k8s)入门学习指南一、什么是Kubernetes?为什么需要它?Kubernetes(k8s)是一个开源的容器编排系统,用于自动化部署、扩展和管理容器化应用程序。它...
欢迎 你 发表评论:
- 一周热门
- 最近发表
- 标签列表
-
- 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)
