Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
为什么你应该更多地使用 attrs_创想鸟

为什么你应该更多地使用 attrs

为什么你应该更多地使用 attrs

介绍

python 的 attrs 库对于希望简化类创建和减少样板代码的开发人员来说是一个游戏规则改变者。这个库甚至受到 nasa 的信任。
attrs 由 hynek schlawack 于 2015 年创建,因其能够自动生成特殊方法并提供干净、声明式的方式来定义类,而迅速成为 python 开发人员最喜欢的工具。
数据类是属性的一种子集。

为什么 attrs 很有用:

减少样板代码提高代码可读性和可维护性提供强大的数据验证和转换功能通过优化实施提高性能

2. 属性入门

安装:
要开始使用 attrs,您可以使用 pip 安装它:

pip install attrs

基本用法:
这是如何使用 attrs 定义类的简单示例:

import attr@attr.sclass person:    name = attr.ib()    age = attr.ib()# creating an instanceperson = person("alice", 30)print(person)  # person(name='alice', age=30)

3. attrs的核心特性

一个。自动方法生成:

attrs 自动为您的类生成 init、repr 和 eq 方法:

@attr.sclass 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 attrfrom typing import list@attr.sclass 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 attrdef must_be_positive(instance, attribute, value):    if value <= 0:        raise valueerror("value must be positive")@attr.sclass 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

4. 高级使用

一个。自定义属性行为:

import attr@attr.sclass 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 demonstrationuser = user("alice", "secret123")print(user)  # user(username='alice')

b.冻结的实例和槽:

@attr.s(frozen=true) # slots=true is the defaultclass point:    x = attr.ib()    y = attr.ib()point = point(1, 2)try:    point.x = 3  # this will raise an attributeerrorexcept attributeerror as e:    print(e)  # can't set attribute

c.工厂函数和初始化后处理:

import attrimport uuid@attr.sclass 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.sclass 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, Factoryfrom typing import List, Optional@defineclass Customer:    id: int    name: str    email: str    orders: List['Order'] = Factory(list)@defineclass Order:    id: int    customer_id: int    total: float    items: List['OrderItem'] = Factory(list)@defineclass OrderItem:    id: int    order_id: int    product_id: int    quantity: int    price: float@defineclass Product:    id: int    name: str    price: float    description: Optional[str] = None# Usagecustomer = 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/↩

以上就是为什么你应该更多地使用 attrs的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1349385.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
初学者如何开始使用 Django 序列化器
上一篇 2025年12月13日 12:49:59
DevOps 中的高级脚本场景:日复一日的 DevOps 工具系列
下一篇 2025年12月13日 12:50:15

相关推荐

发表回复

登录后才能评论
关注微信