【发布时间】:2023-04-01 22:11:01
【问题描述】:
我喜欢与attr 一起工作,并决定阅读一些源代码。引起我注意的一个部分是以下内容 (source):
# Cache this descriptor here to speed things up later.
bound_setattr = _obj_setattr.__get__(self, Attribute)
# Despite the big red warning, people *do* instantiate `Attribute`
# themselves.
bound_setattr("name", name)
bound_setattr("default", default)
bound_setattr("validator", validator)
其中_obj_setattr 定义为object.__setattr__。
我很好奇为什么要这样做。我已经阅读了this stackoverflow 的响应,发现它非常有用,但它没有涵盖关于__get__ 的部分。我读过一些关于descriptors 的文章,但还没有完全理解它们。所以,我的问题是,为什么要使用_obj_setattr.__get__(self, A)("name", name),而不是object.__setattr__(self, "name", name)?
【问题讨论】:
标签: python python-descriptors python-attrs