Python Descriptor (descriptor) That's what this is about.

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.