問題描述
來自 Python 數據模型文檔:p><塊引用>
object.__get__(self, instance, owner=None)
調用以獲取所有者類的屬性(類屬性訪問)或該類的實例(實例屬性訪問).可選的 owner
參數是所有者類,而 instance
是訪問屬性的實例,或者 None
訪問屬性時所有者
.
此方法應返回計算的屬性值或引發 AttributeError
異常.
PEP 252 指定 __get__()
可以用一個或兩個參數調用.Python 自己的內置描述符支持此規范;但是,某些第三方工具可能具有需要兩個參數的描述符.Python 自己的 __getattribute__()
實現總是傳入兩個參數,無論它們是否需要.
object.__set__(self, instance, value)
調用以將所有者類的實例 instance
上的屬性設置為新值 value.
注意,添加 __set__()
或 __delete__()
會將描述符的種類更改為數據描述符".有關詳細信息,請參閱調用描述符.
object.__delete__(self, instance)
調用來刪除所有者類的實例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__ 不獲取?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!