问题描述
可能的重复:
何时以及为什么我可以将描述符类的实例分配给 Python 中的类属性而不是使用属性?
我对何时使用属性和描述符感到困惑.我读到一个属性是一个专门的描述符.
I'm confused as to when to use a property vs a descriptor. I read that a property is a specialized descriptor.
有人可以发布它是如何工作的吗?
Can someone please post how this works?
推荐答案
您应该阅读有关描述符实际是什么的文档.Cliff's Notes 版本:描述符是一种低级机制,可让您挂钩正在访问的对象的属性.属性是这个的高级应用;也就是说,属性是使用描述符实现的.或者,更好的是,属性是 标准库中已经为您提供的描述符.
You should read the docs on what descriptors actually are. The Cliff's Notes version: descriptors are a low-level mechanism that lets you hook into an object's attributes being accessed. Properties are a high-level application of this; that is, properties are implemented using descriptors. Or, better yet, properties are descriptors that are already provided for you in the standard library.
如果您需要一种简单的方法从读取的属性中返回计算值,或在属性写入时调用函数,请使用 @property
装饰器.描述符 API 更灵活,但不太方便,并且在这种情况下可以说是矫枉过正"和不惯用的.它对于更高级的用例很有用,比如实现绑定方法,或者静态和类方法;例如,当您需要知道属性是否是通过类型对象或类型的实例访问时.
If you need a simple way to return a computed value from an attribute read, or to call a function on an attribute write, use the @property
decorator. The descriptor API is more flexible, but less convenient, and arguably "overkill" and non-idiomatic in this situation. It's useful for more advanced use cases, like implementing bound methods, or static and class methods; when you need to know, for example, if the attribute was accessed through the type object, or an instance of the type.
这篇关于Python 描述符与属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!