【发布时间】:2021-02-23 22:46:27
【问题描述】:
我刚刚发现了attrs,它实际上对我即将进行的项目非常有用。在玩耍时,我发现了一些我无法向自己解释的行为。
我有这段代码:
from attr import attrs, attrib, Factory
def validate_dict(instance, attribute, value):
if not isinstance(value, dict):
raise ValueError(f"Attribute `{attribute.name}` has to be of type dict(), not {type(value)}!")
@attrs(kw_only=True, on_setattr=validate_dict)
class FooBar:
defaults = attrib(default=Factory(dict), validator=validate_dict)
config = attrib(default=Factory(dict), validator=validate_dict)
source = attrib(default=Factory(dict), validator=validate_dict)
target = attrib(default=Factory(dict), validator=validate_dict)
>>> foobar = FooBar()
>>> foobar
FooBar(defaults={}, config={}, source={}, target={})
>>> foobar.defaults = {'firstname':'Thomas'}
>>> foobar
FooBar(defaults=None, config={}, source={}, target={})
使用foobar.defaults.update(firstname='Thomas') 有效,foobar = FooBar(defaults={'firstname':'Thomas'}) 也有效,但直接分配也不应该有效吗?还是我使用on_setattr和validator的方式不对?
当我尝试使用 int 设置属性时,即 foobar.defaults = 1,正确引发了 ValueError。
任何提示表示赞赏。问候,托马斯
【问题讨论】:
标签: python python-3.x python-attrs