类和实例

时间:2018-02-03 20:13:25

标签: 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>

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

1 个答案:

答案 0 :(得分:1)

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

请参阅参考datamodel文档的Invoking Descriptors section

  

以下方法仅在包含该方法的类的实例(所谓的描述符类)出现在所有者类中时才适用(描述符必须位于所有者的类字典或类字典中其中一位父母)。

大胆强调我的。这里,所有者类是您访问该属性的实例的类,或者在访问该类的属性的情况下,该类本身是所有者类。 / p>