In python, descriptor (descriptor) is like this, pythondescriptor

Source: Internet
Author: User

In python, descriptor (descriptor) is like this, pythondescriptor

Many tutorials often make descriptor very complex, long articles, and so on.

In fact, a single sentence is used to hook class operations to control behavior.

Most of the time, it is used to block access to instance attributes.
As long as there are _ get _ (), _ set _ (), and _ delete _ () methods in the class. it is a descriptor. let's think about it. If we can't escape the three methods for an operation on a class, we need to hook the methods for any operation we need.
The descriptor is not self host, but parasitic in other classes.
The implementation principles of property, classmethod, staticmethod, and super are exactly the descriptors.

To put it so much, we will use the code below to demonstrate it clearly.

# Coding = utf-8class Integer (object): # Integer is a descriptor, because the _ set _ () method is defined. def _ init _ (self, name): self. name = name def _ set _ (self, instance, value): # Because we only need to hook the behavior of "modifying attributes, therefore, we only need to define the _ set _ () method. We do not need _ get _ () or _ 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 = Point (2, 3) p. x = 9p. x = 9.9 # This statement will throw a TypeError: Expected an int error. this is the role of the descriptor.



In python, fileno does not return a file descriptor. Why?

This is a function. You must use fileno () instead of fileno.

Minor problems encountered by beginners of PYTHON

You open a Write File (w), but try to read it with read!

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.