A lot of tutorials tend to put descriptor into a very complex, long-text, voluminous, results many people look at the foggy.
In fact, in a word, the operation of the class hook, in order to control the behavior.
Most of the time it is used to intercept access to instance properties.
As long as there are __get__ (), __set__ (), and __delete__ () One of the methods in the class. Then it is a descriptor. We think about the operation of a class, can not escape the three methods, we need to control what operation, the hook which method.
The descriptor is not self host, but is parasitic in other classes.
property, Classmethod, Staticmethod, Super's implementation principle is the descriptor.
Say so much, the following code to show, believe clearly.
#coding =utf-8class Integer (object): #Integer就是一个描述器 because the __set__ () method is defined. def __init__ (self, name): self.name = name def __set__ (self, instance, value): #因为我们只需要对 "Modify property" to hook the behavior, So we only define the __set__ () method enough, not __get__ () and __delete__ (). If not isinstance (value, int.): raise TypeError (' expected an int ') instance.__dict__[self.name] = Valueclass Point (Object): x = Integer (' x ') y = integer (' y ') def __init__ (self, x, y): self.x = x self.y = YP = P Oint (2, 3) p.x = 9p.x = 9.9# This sentence throws a typeerror:expected an int error. This is the function of the descriptor.
Python Descriptor (descriptor) That's what this is about.