Python: why can't descriptors be instance variables?

Let's say I define this handle:

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 an attribute of the class and is used 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 attribute of the instance and is not used by the instances.

Why, when value is a descriptor, it can only be an attribute of a class, but when value is a simple integer, does it become an instance attribute?

+4
source share
2 answers

You ignore the instance parameter in your MyDescriptor implementation. That is why it is an attribute of a class. Maybe you want something like this:

 class MyDescriptor(object): def __get__(self, instance, owner): return instance._value def __set__(self, instance, value): instance._value = value def __delete__(self, instance): del(instance._value) 
+8
source

It does not work if you try the code below:

 class MyClass1(object): value = MyDescriptor() value2 = MyDescriptor() c = MyClass1() c.value = 'hello' c.value2 = 'world' # where c.value also equals to "world" 
0
source

All Articles