介绍
python 的 attrs 库对于希望简化类创建和减少样板代码的开发人员来说是一个游戏规则改变者。这个库甚至受到 nasa 的信任。
attrs 由 hynek schlawack 于 2015 年创建,因其能够自动生成特殊方法并提供干净、声明式的方式来定义类,而迅速成为 python 开发人员最喜欢的工具。
数据类是属性的一种子集。
为什么 attrs 很有用:
- 减少样板代码
- 提高代码可读性和可维护性
- 提供强大的数据验证和转换功能
- 通过优化实施提高性能
2. 属性入门
安装:
要开始使用 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)
3. attrs的核心特性
一个。自动方法生成:
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
b.具有类型和默认值的属性定义:
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)
c.验证器和转换器:
import attr
def must_be_positive(instance, attribute, value):
if value
<h2>
4. 高级使用
</h2>
<h3>
一个。自定义属性行为:
</h3>
<pre class="brush:php;toolbar:false">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')
b.冻结的实例和槽:
@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
c.工厂函数和初始化后处理:
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)
5. 最佳实践和常见陷阱
最佳实践:
- 使用类型注释以获得更好的代码可读性和 ide 支持
- 利用验证器确保数据完整性
- 对不可变对象使用冻结类
- 利用自动方法生成来减少代码重复
常见陷阱:
- 忘记在类上使用 @attr.s 装饰器
- 过度使用可能是单独方法的复杂验证器
- 不考虑大量使用工厂函数对性能的影响
6. attrs 与其他库
图书馆 | 特点 | 性能 | 社区 |
---|---|---|---|
属性 | 自动方法生成、具有类型和默认值的属性定义、验证器和转换器 | 比手动代码更好的性能 | 活跃的社区 |
pydantic | 数据验证和设置管理、自动方法生成、具有类型和默认值的属性定义、验证器和转换器 | 表现不错 | 活跃的社区 |
数据类 | 内置于 python 3.7+ 中,使它们更易于访问 | 与python版本绑定 | 内置python库 |
属性和数据类比 pydantic 更快1.
与数据类的比较:
- attrs 功能更加丰富且灵活
- 数据类内置于 python 3.7+ 中,使它们更易于访问
- attrs 在大多数情况下具有更好的性能
- 数据类与 python 版本相关,而 attrs 作为外部库可以与任何 python 版本一起使用。
与pydantic的比较:
- pydantic 专注于数据验证和设置管理
- attrs 更通用,并且与现有代码库集成得更好
- pydantic 内置了 json 序列化,而 attrs 需要额外的库
何时选择属性:
- 对于具有自定义行为的复杂类层次结构
- 当您需要对属性定义进行细粒度控制时
- 对于需要 python 2 兼容性的项目(尽管现在不太相关)
7. 性能和实际应用
性能:
由于其优化的实现,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)
8. 结论和行动呼吁
attrs 是一个功能强大的库,可以简化 python 类定义,同时提供强大的数据验证和操作功能。它能够减少样板代码、提高可读性并增强性能,这使其成为 python 开发人员的宝贵工具。
社区资源:
- github 存储库:https://github.com/python-attrs/attrs
- 文档:https://www.attrs.org/
- pypi 页面:https://pypi.org/project/attrs/
在您的下一个项目中尝试 attrs 并亲身体验它的好处。与社区分享您的经验并为其持续发展做出贡献。快乐编码!
-
https://stefan.sofa-rockers.org/2020/05/29/attrs-dataclasses-pydantic/↩