Python: why can't descriptors be instance variables?

Posted by Continuation on Stack Overflow See other posts from Stack Overflow or by Continuation
Published on 2011-05-10T03:20:09Z Indexed on 2012/09/23 15:38 UTC
Read the original article Hit count: 168

Filed under:
|
|

Say I define this descriptor:

class MyDescriptor(object):

   def __get__(self, instance, owner):
        return self._value

    def __set__(self, instance, value):
        self._value = value

    def __delete__(self, instance):
        del(self._value)

And I use it in this:

class MyClass1(object):
    value = MyDescriptor()


>>> m1 = MyClass1()
>>> m1.value = 1
>>> m2 = MyClass1()
>>> m2.value = 2
>>> m1.value
2

So value is a class attribute and is shared by all instances.

Now if I define this:

class MyClass2(object)
    value = 1

>>> y1 = MyClass2()
>>> y1.value=1
>>> y2 = MyClass2()
>>> y2.value=2
>>> y1.value
1

In this case value is an instance attribute and is not shared by the instances.

Why is it that when value is a descriptor it can only be a class attribute, but when value is a simple integer it becomes an instance attribute?

© Stack Overflow or respective owner

Related posts about python

Related posts about scope