gpt4 book ai didi

python - 为什么 __get__ 拥有所有者而 __set__ 和 __delete__ 没有?

转载 作者:行者123 更新时间:2023-12-04 01:43:59 24 4
gpt4 key购买 nike

来自 Python data model documentation :

object.__get__(self, instance, owner=None)

Called to get the attribute of the owner class (class attribute access) or of an instance of that class (instance attribute access). The optional owner argument is the owner class, while instance is the instance that the attribute was accessed through, or None when the attribute is accessed through the owner.

This method should return the computed attribute value or raise an AttributeError exception.

PEP 252 specifies that __get__() is callable with one or two arguments. Python’s own built-in descriptors support this specification; however, it is likely that some third-party tools have descriptors that require both arguments. Python’s own __getattribute__() implementation always passes in both arguments whether they are required or not.

object.__set__(self, instance, value)

Called to set the attribute on an instance instance of the owner class to a new value, value.

Note, adding __set__() or __delete__() changes the kind of descriptor to a “data descriptor”. See Invoking Descriptors for more details.

object.__delete__(self, instance)

Called to delete the attribute on an instance instance of the owner class.

为什么 __get__ 需要一个 owner__set____delete__ 没有?

这是否意味着当描述符同时提供__get____set__ 时,

  • 我们可以得到一个属性,不管它是属于所有者类的实例还是属于所有者类,
  • 当属性属于所有者类的实例时我们可以设置和删除属性但当它属于所有者类时则不能?

我的问题其实是this one的一部分.

最佳答案

owner 主要用于获取类本身的属性,而不是实例。当您检索实例的属性时,owner 参数是多余的,因为它只是 type(instance)

__set__ 不适用于设置类本身的属性,因此它对 owner 没有用处。

关于python - 为什么 __get__ 拥有所有者而 __set__ 和 __delete__ 没有?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44937813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com