0

I know how descriptors in python work, at least I did before today.

If a class member define __set__(), it is a data descriptor, and foo.member will return foo.member.__get__(foo.member, foo) instead of foo.member object. But it only seems to work if foo.member is defined in a class body, not assigned after class creation

For example, this code returns the descriptor object:

In [1]:  class descr(object):
   ...:         def __get__(self, obj, type=None):
   ...:                 return obj
   ...:         def __set__(self, obj, val):
   ...:                 print('Setting', val, 'to', obj)
   ...:         

In [2]: class C:
   ...:     pass
   ...: 

In [3]: c=C()

In [4]: c.foo=descr()

In [5]: c.foo
Out[5]: <__main__.descr at 0x7fd6450bc4e0>

In [6]: c.foo =5

In [7]: c.foo
Out[7]: 5

While when I define class member in a class body it behaves as expected

In [1]: class descr(object):
    def __get__(self, obj, type=None):
        return obj
    def __set__(self, obj, val):
        print('Setting', val, 'to', obj)
   ...:         

In [2]: class C(object):
    descr=descr()
   ...:     

In [4]: c=C()

In [5]: c.descr
Out[5]: <__main__.C at 0x7fb75011fa50>

In [6]: c.descr=5
('Setting', 5, 'to', <__main__.C object at 0x7fb75011fa50>)

Can anyone detail on that?

Ojomio
  • 843
  • 1
  • 8
  • 17
  • 1
    You're not assigning it to the class, `c` is an instance in that case. Descriptors work at class level. – Ashwini Chaudhary Dec 07 '16 at 12:34
  • Also: https://stackoverflow.com/questions/1004168/why-does-declaring-a-descriptor-class-in-the-init-function-break-the-descrip?rq=1 http://stackoverflow.com/questions/12599972/descriptors-as-instance-attributes-in-python – mata Dec 07 '16 at 12:37

0 Answers0