程序员开发实例大全宝库

网站首页 > 编程文章 正文

Python 中的 10 个高级概念(python 高级语法)

zazugpt 2025-04-02 00:17:25 编程文章 21 ℃ 0 评论

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 class {name}")
        return super().__new__(cls, name, bases, dct)

class MyClass(metaclass=Meta):
    pass

3. 协程

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

import asyncio

async def async_task():
    print("Task started")
    await asyncio.sleep(1)
    print("Task completed")

asyncio.run(async_task())

4. 抽象基类 (ABC)

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

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def sound(self):
        pass

class 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 * 2

class MyClass:
    attribute = Descriptor()

obj = MyClass()
obj.attribute = 10
print(obj.attribute)  # Output: 20

6. 线程和多处理

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

import threading

def 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

@dataclass
class Point:
    x: int
    y: int

p = Point(10, 20)
print(p)  # Output: Point(x=10, y=20)

9. 推导式

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

# Nested comprehension
matrix = [[j for j in range(3)] for i in range(3)]
print(matrix)

# With conditions
squares = [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 StopIteration

iterator = MyIterator(5)
for value in iterator:
    print(value)

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表