class 和实例上的描述符行为差异
descriptor behavior difference on class and instance
我试图理解 python 中的描述符,我注意到的一件事如下:
In [1]: class descriptor:
...: def __init__(self):
...: pass
...: def __get__(self, instance, owner):
...: print ("__get__ called")
...: return 0
...: def __set__(self, obj, value):
...: print ("__set__ called")
In [2]: class Foo:
...: y = descriptor()
...: def __init__(self):
...: self.x = descriptor()
In [3]: Foo.y
__get__ called
Out[3]: 0
In [4]: f = Foo()
In [5]: f.x
Out[5]: <__main__.descriptor at 0x1099dd588>
如您所见,在 class 属性上,描述符的 __get__
被正确调用,但在实例属性上它没有调用所需的方法。我尝试阅读 this,但该页面的哪一部分适用于此处并不是很明显。
描述符仅在 class、从不 实例上受支持。
参见参考数据模型文档的Invoking Descriptors section:
The following methods only apply when an instance of the class containing the method (a so-called descriptor class) appears in an owner class (the descriptor must be in either the owner’s class dictionary or in the class dictionary for one of its parents).
大胆强调我的。这里,owner class 是您访问属性的实例的 class,或者如果访问 class 上的属性, class 本身就是 所有者 class.
我试图理解 python 中的描述符,我注意到的一件事如下:
In [1]: class descriptor:
...: def __init__(self):
...: pass
...: def __get__(self, instance, owner):
...: print ("__get__ called")
...: return 0
...: def __set__(self, obj, value):
...: print ("__set__ called")
In [2]: class Foo:
...: y = descriptor()
...: def __init__(self):
...: self.x = descriptor()
In [3]: Foo.y
__get__ called
Out[3]: 0
In [4]: f = Foo()
In [5]: f.x
Out[5]: <__main__.descriptor at 0x1099dd588>
如您所见,在 class 属性上,描述符的 __get__
被正确调用,但在实例属性上它没有调用所需的方法。我尝试阅读 this,但该页面的哪一部分适用于此处并不是很明显。
描述符仅在 class、从不 实例上受支持。
参见参考数据模型文档的Invoking Descriptors section:
The following methods only apply when an instance of the class containing the method (a so-called descriptor class) appears in an owner class (the descriptor must be in either the owner’s class dictionary or in the class dictionary for one of its parents).
大胆强调我的。这里,owner class 是您访问属性的实例的 class,或者如果访问 class 上的属性, class 本身就是 所有者 class.