← Back to DAGDA | Support | Source: https://github.com/hellowac/attrs-zh-cn
Skip to content

About

Python Classes Without Boilerplate

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

 
 

Repository files navigation

attrs

Documentation License: MIT Downloads per month DOI

attrs 是一个 Python 包,它将通过免除你实现对象协议(即 双下方法)的繁琐工作,重新带回编写类的乐趣。自 2020 年以来,它已被 NASA 信赖 并用于火星任务!

它的主要目标是帮助你编写简洁且正确的软件,同时不降低代码的执行效率。

赞助商

attrs 项目离不开我们 优秀的赞助商 的支持。 特别是那些慷慨支持我们 The Organization 级别及更高级别的赞助商:

请考虑加入他们,帮助使 attrs 的维护更加可持续!

示例

attrs 提供了一个类装饰器,以及一种声明式定义类属性的方式:

>>> from attrs import asdict, define, make_class, Factory

>>> @define
... class SomeClass:
...     a_number: int = 42
...     list_of_numbers: list[int] = Factory(list)
...
...     def hard_math(self, another_number):
...         return self.a_number + sum(self.list_of_numbers) * another_number


>>> sc = SomeClass(1, [1, 2, 3])
>>> sc
SomeClass(a_number=1, list_of_numbers=[1, 2, 3])

>>> sc.hard_math(3)
19
>>> sc == SomeClass(1, [1, 2, 3])
True
>>> sc != SomeClass(2, [3, 2, 1])
True

>>> asdict(sc)
{'a_number': 1, 'list_of_numbers': [1, 2, 3]}

>>> SomeClass()
SomeClass(a_number=42, list_of_numbers=[])

>>> C = make_class("C", ["a", "b"])
>>> C("foo", "bar")
C(a='foo', b='bar')

在声明了属性之后,attrs 为你提供:

  • 简洁明了的类属性概览,
  • 人类可读的 __repr__,
  • 等值检查方法,
  • 初始化器,
  • 以及更多功能,

不需要重复编写无聊的样板代码,并且不会带来运行时性能的损失。


这个例子使用了 attrs 现代 API,它在 20.1.0 版本中引入,而 attrs 包的导入名称则在 21.3.0 版本中加入。 经典 API(如 @attr.s、attr.ib 以及它们的正式别名)和 attr 包的导入名称将无限期保留。

查看 关于核心 API 名称 了解详细解释!

讨厌类型注解!?

没问题! 在 attrs 中,类型是完全可选的。 你可以简单地将 attrs.field() 赋值给属性,而不是使用类型注解:

from attrs import define, field

@define
class SomeClass:
    a_number = field(default=42)
    list_of_numbers = field(factory=list)

数据类

乍一看,attrs 可能让你联想到 dataclasses(事实上,dataclasses 确实是 attrs 的后代)。 但在实际应用中,attrs 提供了更多的功能,并且更灵活。 例如,它允许你定义NumPy 数组的特殊处理,以进行相等性检查,提供了更多的方式来接入初始化过程,并提供了 __init_subclass__ 的替代方法,甚至允许你通过调试器逐步执行生成的方法。

想了解更多细节,请查看我们的对比页面,但一般来说,我们更有可能为了实现某些预期的功能而“打破常规”,尽管这些功能在实际操作中可能非常复杂。

项目信息

面向企业的 attrs

可作为 Tidelift 订阅服务 的一部分提供。

attrs 的维护者与数千个其他包的开发者正在与 Tidelift 合作,为你在构建应用程序时使用的开源包提供商业支持和维护。 节省时间,降低风险,改善代码健康,同时为你实际使用的包的维护者提供报酬。

About

Python Classes Without Boilerplate

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages