为什么__get__拥有所有者,而__set__和__delete__却没有? [英] Why does __get__ take an owner while __set__ and __delete__ do not?
问题描述
从Python 数据模型文档:>
object .__ get __(self,instance,owner = None)
被调用以获取所有者类的属性(类属性访问)或该类的实例的属性(实例属性访问).可选的
owner
参数是所有者类,而instance
是通过其访问属性的实例,或者是None
通过该属性访问时的实例.所有者
.此方法应返回计算出的属性值或引发
AttributeError
异常.PEP 252指定可以使用一个或两个参数调用
__ get __()
.Python自己的内置描述符支持此规范.但是,某些第三方工具可能具有同时需要两个参数的描述符.不管是否需要,Python自己的__ getattribute __()
实现总是传递两个参数.
object .__ set __(自身,实例,值)
被调用以将所有者类的实例
instance
上的属性设置为新值,即值.请注意,添加
__ set __()
或__ delete __()
会将描述符的类型更改为数据描述符".有关更多详细信息,请参见调用描述符.
object .__ delete __(自己,实例)
被调用以删除所有者类的实例
instance
上的属性.
为什么 __ get __
不带 owner
,而 __ set __
和 __ delete __
不带?
这是否意味着当描述符同时提供 __ get __
和 __ set __
时,
- 无论属性是属于所有者类的实例还是属于所有者类,我们都可以获取属性,
- 当属性属于所有者类的实例时,我们可以设置和删除一个属性吗?
我的问题实际上是这个问题的一部分.
owner
主要用于获取类本身的属性,而不是实例.当您在实例上检索属性时, owner
参数是多余的,因为它只是 type(instance)
.
__ set __
不适用于在类本身上设置属性,因此它对 owner
而言毫无用处.
From the 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, whileinstance
is the instance that the attribute was accessed through, orNone
when the attribute is accessed through theowner
.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.
Why does __get__
take an owner
while __set__
and __delete__
do not?
Does it mean that when a descriptor supplies both __get__
and __set__
,
- we can get an attribute no matter whether it belongs to an instance of the owner class or to the owner class,
- we can set and delete an attribute when it belongs to an instance of the owner class but not when it belongs to the owner class?
My question is actually part of this one.
owner
mostly exists for getting the attribute on the class itself, rather than an instance. When you're retrieving the attribute on an instance, the owner
argument is redundant, since it's just type(instance)
.
__set__
doesn't apply to setting the attribute on the class itself, so it has no use for owner
.
这篇关于为什么__get__拥有所有者,而__set__和__delete__却没有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!