the output in reference of descriptor.

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Aug 24 03:18:13 EDT 2014


luofeiyu wrote:

> let me paste it again to make my question more clear:
> 
>      >>>c2.d
>      __get__() is called <__main__.C2 object at 0x000000000297BE10>
> <class '__main__.C2'>
>      <__main__.C object at 0x000000000297BBA8>

You have an instance c2. You do an attribute lookup on d, which is a
descriptor, so d.__get__ is called. d.__get__ prints a status line, then
returns d's "self", which is an instance of C, not C2.

Because you are in the interactive interpreter, the returned result is
printed. Otherwise, it would be ignored.


>      >>> c2.d.a
>      __get__() is called <__main__.C2 object at 0x000000000297BE10>
> <class '__main__.C2'>
>      __getattribute__() is called
>      'abc'

This is the same as:

temp = c2.d
print(temp.a)

which is the same as:

temp = C()
print(temp.a)


> Why the result of c2.d.a  is not :
> 
>      __get__() is called <__main__.C2 object at 0x000000000297BE10>
> <class __main__.C2'>
>      <__main__.C object at 0x000000000297BBA8>
>      __getattribute__() is called
>      'abc'
> 
> Why the` return self` in the __get__ method in class C  does not work?

Of course it works. It returns the instance of C, then Python looks up
attribute "a" on that instance.


> Why there is no <__main__.C object at 0x000000000297BBA8>  in the output?

Because you didn't print it. If you want to see that, you can do:

temp = c2.d
print(temp)
print(temp.a)


In the interactive interpreter, but nowhere else, the final result of each
calculation is printed:

py> 1 + 2
3
py> 1 + 2 + 3 + 4 + 5
15

You should not expect it to do this:

py> 1 + 2 + 3 + 4 + 5
3
6
10
15


Only the last result is printed. The same applies for the . operator:

instance.a.b.c.d.e

will only print the final result, not

instance.a
instance.a.b
instance.a.b.c
instance.a.b.c.d
instance.a.b.c.d.e


-- 
Steven




More information about the Python-list mailing list