【发布时间】:2021-10-09 13:45:24
【问题描述】:
假设我们有一个attrs 类:
@attr.s()
class Foo:
a: bool = attr.ib(default=False)
b: int = attr.ib(default=5)
@b.validator
def _check_b(self, attribute, value):
if not self.a:
raise ValueError("to define 'b', 'a' must be True")
if value < 0:
raise ValueError("'b' has to be a positive integer")
所以下面的行为是正确的:
>>> Foo(a=True, b=10)
Foo(a=True, b=10)
>>> Foo(b=10)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<attrs generated init __main__.Foo>", line 5, in __init__
__attr_validator_b(self, __attr_b, self.b)
File "<input>", line 9, in _check_b
ValueError: to define 'b', 'a' must be True
但这不是:
>>> Foo()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<attrs generated init __main__.Foo>", line 5, in __init__
__attr_validator_b(self, __attr_b, self.b)
File "<input>", line 9, in _check_b
ValueError: to define 'b', 'a' must be True
这显然是因为Foo.b 总是被初始化,不管Foo.a 何时被赋予值:通过默认值或Foo.__init__。
是否有任何初始化钩子来完成这个属性依赖?
【问题讨论】:
标签: python python-attrs