when the method __get__ will be called?

Peter Otten __peter__ at web.de
Fri Aug 22 03:27:00 EDT 2014


luofeiyu wrote:

> class C(object):
>      a = 'abc'
>      def __getattribute__(self, *args, **kwargs):
>          print("__getattribute__() is called")
>          return object.__getattribute__(self, *args, **kwargs)
>      def __getattr__(self, name):
>          print("__getattr__() is called ")
>          return name + " from getattr"
>      def __get__(self, instance, owner):
>          print("__get__() is called", instance, owner)
>          return self
>      def foo(self, x):
>          print(x)
> 
> 
>  >>> x=C()
>  >>> x.a
> __getattribute__() is called
> 'abc'
>  >>> x.b
> __getattribute__() is called
> __getattr__() is called
> 'b from getattr'
> 
> 
> 
> 
> If call an attribute which does exist ,__getattribute__() is called
> If call an attribute which does not  exist ,__getattribute__() is called
> and then __getattr__() is called ?

You typically use either __getattribute__() which is called for every 
attribute or __getattr__() which is called only as a fallback when an 
attribute is not found in the instance __dict__.

> when the __get__ method will be called?no chance for my example?

__get__() is part of the descriptor protocol; it is called on attribute 
access:

>>> class A(object):
...     c = C()
... 
>>> A().c
('__get__() is called', <__main__.A object at 0x7f7cc2c8e850>, <class 
'__main__.A'>)
<__main__.C object at 0x7f7cc2c8e910>
>>> A.c
('__get__() is called', None, <class '__main__.A'>)
<__main__.C object at 0x7f7cc2c8e910>





More information about the Python-list mailing list