python - 类和实例上的描述符行为差异

标签 python python-3.6 propertydescriptor

我试图理解 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>

如您所见,在类属性上,描述符的 __get__正在被正确调用,但在实例属性上它没有调用所需的方法。我尝试阅读this ,但该页面的哪一部分适用于此处并不是很明显。

最佳答案

描述符仅在类上受支持,在实例上从不受支持。

请参阅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).

大胆强调我的。这里,所有者类是您访问其属性的实例的类,或者如果访问该类的属性,则该类本身就是所有者类

关于python - 类和实例上的描述符行为差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48601563/

相关文章:

python - 在 Python 中运行 C 扩展比普通 C 更快

python - 创建每个实例的属性描述符?

java - 使用反射在 jaxb 对象上设置 ArrayList 值时出现问题

python - 对 linux 服务器的 ajax 请求有时会返回答案,有时会返回错误 500

python - Twine 在不提示输入密码的情况下挂起

Python:描述符列表

python - tempfile.TemporaryDirectory 上下文管理器不使用/tmp 文件夹

python - 安装 pywin32 时出错(在 Ubuntu 上)

android - 是否有解决 Android 错误 "Unable to resolve virtual method java/beans/PropertyDescriptor"的方法?

Python 或 LibreOffice 保存使用密码加密的 xlsx 文件