2

While learning about descriptors in Python, I tried the following code:

class D(object) :

    def __init__(s) :
        s.a = ''

    def __get__(s, ins, own) :
        print 'desc get'
        return s.a

    def __set__(s, ins, val) :
        print 'desc set'
        s.a = val


class C(object) :
    d = D()


C.d = 'danger'
c = C()
c.d = 'some str'

Why is it that when C.d = 'danger' is executed, the descriptor is removed from C.__dict__?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
user3282758
  • 1,379
  • 11
  • 29
  • Just a quick remark, in python, we usually use `self` rather than `s` to represent the instance (in your methods) – Paco May 13 '15 at 16:50
  • I think you're looking for "classmethod properties" http://stackoverflow.com/a/1800999/3399373 – Navith May 13 '15 at 17:10

1 Answers1

3

In your example, when you make this affectation C.d = 'danger' you are overwriting the descriptor by the value 'danger'. C.d is no longer a descriptor, it's now the string 'danger'.

vinz
  • 382
  • 2
  • 10
  • you mean if there is another descriptor class `class NewD` and if I say `c.d = NewD()` then `c.d` would be a new descriptor. Okkk – user3282758 May 13 '15 at 17:11
  • Only if you do that on the class property itself... `c.d == NewD()` make a call to `D.__set__(c.d, c, NewD())`, but `C.d == NewD()` replace the d property of class C – vinz May 13 '15 at 17:15
  • I did not understand your comment. At both places you are using `==` – user3282758 May 13 '15 at 17:19
  • actually I meant `C.d = newD()` in my earlier comment. Sorry for the typing mistake - it completely changed my statement – user3282758 May 13 '15 at 17:21
  • sorry, it was a typo... I meant using the `=` – vinz May 14 '15 at 21:48