attrs

Utilities

无类样板

概述 attrs

attrs(作为 attr 导入)是一个 Python 包,可让您编写简洁、正确的 Python 类,而无需样板。它自动生成 __init__、__repr__、__eq__ 和其他 dunder 方法,并且还支持验证器、转换器、槽和冻结(不可变)类。

attrs 是在 Python 中定义干净的数据保存类的流行选择,它直接启发了 Python 的内置 dataclasses 模块。在PyRun中,attrs 通过 micropip 立即加载,使其成为学习类设计模式时值得探索的绝佳库。

代码和执行输出

使用 attrs 验证器清理 Python 类。

Attrs Data Classes在编辑器中运行
import attr

@attr.s(auto_attribs=True)
class Point:
    x: float
    y: float

    def distance_to(self, other: "Point") -> float:
        return ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5

@attr.s(auto_attribs=True)
class Polygon:
    name: str
    vertices: list = attr.Factory(list)

    def perimeter(self) -> float:
        pts = self.vertices + [self.vertices[0]]
        return sum(pts[i].distance_to(pts[i+1]) for i in range(len(pts)-1))

triangle = Polygon("Triangle", [
    Point(0, 0), Point(4, 0), Point(0, 3)
])

print(repr(triangle))
print(f"Perimeter: {triangle.perimeter():.4f}")
print(f"Expected : 12.0000  (3-4-5 right triangle)")

相关套餐

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。