Use cases for property vs. descriptor vs. __getattribute__

前端 未结 2 1362
温柔的废话
温柔的废话 2021-02-02 14:25

The question refers to which one is preferable to be used in which use case, not about the technical background.

In python, you can control the access o

2条回答
  •  爱一瞬间的悲伤
    2021-02-02 15:15

    __getattribute__ is the hook that enables property (and other descriptors) to work in the first place and is called for all attribute access on an object. Consider it a lower-level API when a property or even a custom descriptor is not enough for your needs. __getattr__ is called by __getattribute__ when no attribute has been located through other means, as a fallback.

    Use property for dynamic attributes with a fixed name, __getattr__ for attributes of a more dynamic nature (e.g. a series of attributes that map to values in an algorithmic manner).

    Descriptors are used when you need to bind arbitrary objects to an instance. When you need to replace method objects with something more advanced for example; a recent example is a class-based decorator wrapping methods that needed to support additional attributes and methods on the method object. Generally, when you are still thinking in terms of scalar attributes, you don't need descriptors.

提交回复
热议问题