To illustrate the question check the following code:
class MyDescriptor(object): def __get__(self, obj, type=None): print 'get', self, obj, type return self._v def __set__(self, obj, value): self._v = value print 'set', self, obj, value return None class SomeClass1(object): m = MyDescriptor() class SomeClass2(object): def __init__(self): self.m = MyDescriptor() x1 = SomeClass1() x2 = SomeClass2() x1.m = 1000 # -> set <__main__.MyDescriptor object at 0xb787c7ec> <__main__.SomeClass1 object at 0xb787cc8c> 10000 x2.m = 1000 # I guess that this overwrites the function. But why? # -> print x1.m # -> get <__main__.MyDescriptor object at 0xb787c7ec> <__main__.SomeClass1 object at 0xb787cc8c> <class '__main__.SomeClass1'> 10000 print x2.m # -> 10000
- Why doesn’t x2.m = 1000 not call the __set__-function? It seems that this overwrites the function. But why?
- Where is _v in x1? It is not in x1._v
To answer your second question, where is
_v?Your version of the descriptor keeps
_vin the descriptor itself. Each instance of the descriptor (the class-level instanceSomeClass1, and all of the object-level instances in objects of classSomeClass2will have distinct values of_v.Look at this version. This version updates the object associated with the descriptor. This means the object (
SomeClass1orx2) will contain the attribute_v.