百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

你可能不知道的实用 Python 功能(python有哪些用)

off999 2025-06-15 18:36 16 浏览 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}")

相关推荐

让 Python 代码飙升330倍:从入门到精通的四种性能优化实践

花下猫语:性能优化是每个程序员的必修课,但你是否想过,除了更换算法,还有哪些“大招”?这篇文章堪称典范,它将一个普通的函数,通过四套组合拳,硬生生把性能提升了330倍!作者不仅展示了“术”,更传授...

7 段不到 50 行的 Python 脚本,解决 7 个真实麻烦:代码、场景与可复制

“本文整理自开发者AbdurRahman在Stackademic的真实记录,所有代码均经过最小化删减,确保在50行内即可运行。每段脚本都对应一个日常场景,拿来即用,无需额外依赖。一、在朋...

Python3.14:终于摆脱了GIL的限制

前言Python中最遭人诟病的设计之一就是GIL。GIL(全局解释器锁)是CPython的一个互斥锁,确保任何时刻只有一个线程可以执行Python字节码,这样可以避免多个线程同时操作内部数据结...

Python Web开发实战:3小时从零搭建个人博客

一、为什么选Python做Web开发?Python在Web领域的优势很突出:o开发快:Django、Flask这些框架把常用功能都封装好了,不用重复写代码,能快速把想法变成能用的产品o需求多:行业...

图解Python编程:从入门到精通系列教程(附全套速查表)

引言本系列教程展开讲解Python编程语言,Python是一门开源免费、通用型的脚本编程语言,它上手简单,功能强大,它也是互联网最热门的编程语言之一。Python生态丰富,库(模块)极其丰富,这使...

Python 并发编程实战:从基础到实战应用

并发编程是提升Python程序效率的关键技能,尤其在处理多任务场景时作用显著。本文将系统介绍Python中主流的并发实现方式,帮助你根据场景选择最优方案。一、多线程编程(threading)核...

吴恩达亲自授课,适合初学者的Python编程课程上线

吴恩达教授开新课了,还是亲自授课!今天,人工智能著名学者、斯坦福大学教授吴恩达在社交平台X上发帖介绍了一门新课程——AIPythonforBeginners,旨在从头开始讲授Python...

Python GUI 编程:tkinter 初学者入门指南——Ttk 小部件

在本文中,将介绍Tkinter.ttk主题小部件,是常规Tkinter小部件的升级版本。Tkinter有两种小部件:经典小部件、主题小部件。Tkinter于1991年推出了经典小部件,...

Python turtle模块编程实践教程

一、模块概述与核心概念1.1turtle模块简介定义:turtle是Python标准库中的2D绘图模块,基于Logo语言的海龟绘图理念实现。核心原理:坐标系系统:原点(0,0)位于画布中心X轴:向右...

Python 中的asyncio 编程入门示例-1

Python的asyncio库是用于编写并发代码的,它使用async/await语法。它为编写异步程序提供了基础,通过非阻塞调用高效处理I/O密集型操作,适用于涉及网络连接、文件I/O...

30天学会Python,开启编程新世界

在当今这个数字化无处不在的时代,Python凭借其精炼的语法架构、卓越的性能以及多元化的应用领域,稳坐编程语言排行榜的前列。无论是投身于数据分析、人工智能的探索,还是Web开发的构建,亦或是自动化办公...

Python基础知识(IO编程)

1.文件读写读写文件是Python语言最常见的IO操作。通过数据盘读写文件的功能都是由操作系统提供的,读写文件就是请求操作系统打开一个文件对象(通常称为文件描述符),然后,通过操作系统提供的接口从这个...

Python零基础到精通,这8个入门技巧让你少走弯路,7天速通编程!

Python学习就像玩积木,从最基础的块开始,一步步搭建出复杂的作品。我记得刚开始学Python时也是一头雾水,走了不少弯路。现在回头看,其实掌握几个核心概念,就能快速入门这门编程语言。来聊聊怎么用最...

一文带你了解Python Socket 编程

大家好,我是皮皮。前言Socket又称为套接字,它是所有网络通信的基础。网络通信其实就是进程间的通信,Socket主要是使用IP地址,协议,端口号来标识一个进程。端口号的范围为0~65535(用户端口...

Python-面向对象编程入门

面向对象编程是一种非常流行的编程范式(programmingparadigm),所谓编程范式就是程序设计的方法论,简单的说就是程序员对程序的认知和理解以及他们编写代码的方式。类和对象面向对象编程:把...

取消回复欢迎 发表评论: