“The following methods only apply when an instance of the class containing the method (a so-called descriptor class) appears in the class dictionary of another new-style class, known as the owner class. ”
这里的following methods是指下面三个方法:
object.__get__(self, instance, owner) Called to get the attribute of the owner class (class attribute access) or of an instance of that class (instance attribute access). owner is always 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.
object.__set__(self, instance, value) Called to set the attribute on an instance instance of the owner class to a new value, value.
object.__delete__(self, instance) Called to delete the attribute on an instance instance of the owner class.
class OverridingDescriptor(object):
def __init__(self, value= "Data value"):
self._value = value
def __get__(self, obj, type = None):
print self, obj, type
return self._value
def __set__(self, obj, value):
print self, obj, value
self._value = value
class Foo(object):
name = OverridingDescriptor()
if __name__ == "__main__":
print Foo.name
Foo.name ="smith"
print Foo.name
首先我们看第一句 print Foo.name 的输出 :
None
No-data value
很明显直接调用了直接调用了Descriptor的__get__方法。我们都知道python中的property是提供了对object属性提供了封装,那这里我们推断会不会descriptor提供了对object自身的封装呢?我们接着分析,这时候我们发现第二句的代码没有输出,而最后一句代码的输出是:
smith
也就是说这里没有调用descriptor的__set__方法,这又是为什么呢?这里又涉及到python对于descriptor的查找策略, 而python对于descriptor中的__get__/__set__又采取了两种不同的策略: