python 的 attrs 库对于希望简化类创建和减少样板代码的开发人员来说是一个游戏规则改变者。这个库甚至受到 nasa 的信任。
attrs 由 hynek schlawack 于 2015 年创建,因其能够自动生成特殊方法并提供干净、声明式的方式来定义类,而迅速成为 python 开发人员最喜欢的工具。
数据类是属性的一种子集。
为什么 attrs 很有用:
安装:
要开始使用 attrs,您可以使用 pip 安装它:
pip install attrs
基本用法:
这是如何使用 attrs 定义类的简单示例:
import attr @attr.s class person: name = attr.ib() age = attr.ib() # creating an instance person = person("alice", 30) print(person) # person(name='alice', age=30)
attrs 自动为您的类生成 init、repr 和 eq 方法:
@attr.s class book: title = attr.ib() author = attr.ib() year = attr.ib() book1 = book("1984", "george orwell", 1949) book2 = book("1984", "george orwell", 1949) print(book1) # book(title='1984', author='george orwell', year=1949) print(book1 == book2) # true
import attr from typing import list @attr.s class library: name = attr.ib(type=str) books = attr.ib(type=list[str], default=attr.factory(list)) capacity = attr.ib(type=int, default=1000) library = library("city library") print(library) # library(name='city library', books=[], capacity=1000)
import attr def must_be_positive(instance, attribute, value): if value <= 0: raise valueerror("value must be positive") @attr.s class product: name = attr.ib() price = attr.ib(converter=float, validator=[attr.validators.instance_of(float), must_be_positive]) product = product("book", "29.99") print(product) # product(name='book', price=29.99) try: product("invalid", -10) except valueerror as e: print(e) # value must be positive
import attr @attr.s class user: username = attr.ib() _password = attr.ib(repr=false) # exclude from repr @property def password(self): return self._password @password.setter def password(self, value): self._password = hash(value) # simple hashing for demonstration user = user("alice", "secret123") print(user) # user(username='alice')
@attr.s(frozen=true) # slots=true is the default class point: x = attr.ib() y = attr.ib() point = point(1, 2) try: point.x = 3 # this will raise an attributeerror except attributeerror as e: print(e) # can't set attribute
import attr import uuid @attr.s class order: id = attr.ib(factory=uuid.uuid4) items = attr.ib(factory=list) total = attr.ib(init=false) def __attrs_post_init__(self): self.total = sum(item.price for item in self.items) @attr.s class item: name = attr.ib() price = attr.ib(type=float) order = order(items=[item("book", 10.99), item("pen", 1.99)]) print(order) # order(id=uuid('...'), items=[item(name='book', price=10.99), item(name='pen', price=1.99)], total=12.98)
图书馆 | 特点 | 性能 | 社区 |
---|---|---|---|
属性 | 自动方法生成、具有类型和默认值的属性定义、验证器和转换器 | 比手动代码更好的性能 | 活跃的社区 |
pydantic | 数据验证和设置管理、自动方法生成、具有类型和默认值的属性定义、验证器和转换器 | 表现不错 | 活跃的社区 |
数据类 | 内置于 python 3.7+ 中,使它们更易于访问 | 与python版本绑定 | 内置python库 |
属性和数据类比 pydantic 更快1.
性能:
由于其优化的实现,attrs 通常比手动编写的类或其他库提供更好的性能。
现实世界的例子:
from attr import define, Factory from typing import List, Optional @define class Customer: id: int name: str email: str orders: List['Order'] = Factory(list) @define class Order: id: int customer_id: int total: float items: List['OrderItem'] = Factory(list) @define class OrderItem: id: int order_id: int product_id: int quantity: int price: float @define class Product: id: int name: str price: float description: Optional[str] = None # Usage customer = Customer(1, "Alice", "alice@example.com") product = Product(1, "Book", 29.99, "A great book") order_item = OrderItem(1, 1, 1, 2, product.price) order = Order(1, customer.id, 59.98, [order_item]) customer.orders.append(order) print(customer)
attrs 是一个功能强大的库,可以简化 python 类定义,同时提供强大的数据验证和操作功能。它能够减少样板代码、提高可读性并增强性能,这使其成为 python 开发人员的宝贵工具。
社区资源:
在您的下一个项目中尝试 attrs 并亲身体验它的好处。与社区分享您的经验并为其持续发展做出贡献。快乐编码!
https://stefan.sofa-rockers.org/2020/05/29/attrs-dataclasses-pydantic/↩