when the method __get__ will be called?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Aug 22 03:30:33 EDT 2014


Luofeiyu, you are asking very advanced questions. How experienced with
Python are you? Asking about __get__ is nearly never needed. __get__ is
used internally by built-ins like property, classmethod and staticmethod.
99.99% of Python programmers will never need to write a __get__ method, and
of the 0.01% who do, they might only write one or two in their whole
career.


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)


[...]
> 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 ?

Correct.

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

No chance for your example. __get__ is used in the "descriptor protocol",
used for methods and properties. You can see __get__ called here:


class D(object):
    foo = C()

d = D()
d.foo


Now C.__get__ will be called.



-- 
Steven




More information about the Python-list mailing list