Python中的10个高级概念

自由坦荡的智能 2025-03-18 00:33:46

1. 上下文管理器

上下文管理器用于管理资源,例如文件或数据库连接,确保在使用后进行适当清理。它们是使用 with 语句实现的。

with open("file.txt", "w") as file: file.write("Hello, World!")# File is automatically closed after exiting the block.2. 元类

元类控制类的创建和行为。它们是类中的类,决定了类本身的行为方式。

class Meta(type): def __new__(cls, name, bases, dct): print(f"Creating {name}") return super().__new__(cls, name, bases, dct)class MyClass(metaclass=Meta): pass3. 协程

协程通过使用 async 和 await 关键字暂停和恢复执行来允许异步编程。

import asyncioasync def async_task(): print("Task started") await asyncio.sleep(1) print("Task completed")asyncio.run(async_task())4. 抽象基类 (ABC)

ABC 为其他类定义蓝图,确保派生类实现特定方法。

from abc import ABC, abstractmethodclass Animal(ABC): @abstractmethod def sound(self): passclass Dog(Animal): def sound(self): return "Woof!"dog = Dog()print(dog.sound())5. 描述符

描述符管理属性的行为,并提供对获取、设置和删除属性值的精细控制。

class Descriptor: def __get__(self, instance, owner): return instance._value def __set__(self, instance, value): instance._value = value * 2class MyClass: attribute = Descriptor()obj = MyClass()obj.attribute = 10print(obj.attribute) # Output: 206. 线程和多处理

这些用于并行执行,从而启用并发任务。

import threadingdef task(): print("Task executed")thread = threading.Thread(target=task)thread.start()thread.join()7. 鸭子类型和多态性

Python 强调 “duck typing”,其中对象的类型不如它定义的方法和属性重要。

class Bird: def fly(self): print("Flying")class Airplane: def fly(self): print("Flying with engines")def test_fly(obj): obj.fly()test_fly(Bird())test_fly(Airplane())8. 数据类

@dataclass 在 Python 3.7 中引入,是一个装饰器,可简化用于存储数据的类创建。

from dataclasses import dataclass@dataclassclass Point: x: int y: intp = Point(10, 20)print(p) # Output: Point(x=10, y=20)9. 推导式

Python 允许在推导式中使用嵌套和条件逻辑。

# Nested comprehensionmatrix = [[j for j in range(3)] for i in range(3)]print(matrix)# With conditionssquares = [x**2 for x in range(10) if x % 2 == 0]print(squares)10. 自定义迭代器

自定义迭代器允许您控制如何迭代对象。

class MyIterator: def __init__(self, max): self.max = max self.current = 0 def __iter__(self): return self def __next__(self): if self.current < self.max: self.current += 1 return self.current else: raise StopIterationiterator = MyIterator(5)for value in iterator: print(value)
0 阅读:0

自由坦荡的智能

简介:感谢大家的关注