The descriptor in Python is a simple user guide, which is pythondescriptor.

Source: Internet
Author: User

The descriptor in Python is a simple user guide, which is pythondescriptor.

When defining the iterator, the description is the object that implements the iteration protocol, that is, the object that implements the _ iter _ method. Similarly, the descriptor implements the descriptor Protocol, namely, the object of the _ get __, _ set __, and _ delete _ methods.

The definition is abstract. Talk is cheap. Check the Code:

class WebFramework(object):  def __init__(self, name='Flask'):    self.name = name  def __get__(self, instance, owner):    return self.name  def __set__(self, instance, value):    self.name = valueclass PythonSite(object):  webframework = WebFramework()In [1]: PythonSite.webframeworkOut[1]: 'Flask'In [2]: PythonSite.webframework = 'Tornado'In [3]: PythonSite.webframeworkOut[3]: 'Tornado'

Defines a class WebFramework, which implements the descriptor Protocol _ get _ and _ set __. this object (the class is also an object, everything is an object) is converted into a descriptor. The implementation of _ get _ and _ set _ is called the data descriptor ). Only the implementations of _ get _ are non-descriptors. The difference between the two is the priority of the dictionary relative to the instance.

If the instance dictionary has an attribute with the same name as the descriptor, if the descriptor is a data descriptor, the data descriptor is preferred. If the descriptor is not a data descriptor, the attributes in the dictionary are preferred.

Descriptor call
For such magic, its calling method is often not used directly. For example, the decorator needs to be called with the @ symbol. The iterator is usually in the iteration process or called using the next method. The descriptor is relatively simple and called when the object property is used.

In [15]: webframework = WebFramework()In [16]: webframework.__get__(webframework, WebFramework)Out[16]: 'Flask'

Describer Application
The descriptor mainly serves to define methods and attributes. Since we can re-Describe the attributes of the class, this magic can change some behaviors of the class. The simplest application is to write the cache of A Class Attribute in combination with the decorator. The author of Flask wrote a werkzeug network tool library, which uses the characteristics of the descriptor to implement a cache.

class _Missing(object):  def __repr__(self):    return 'no value'  def __reduce__(self):    return '_missing'_missing = _Missing()class cached_property(object):  def __init__(self, func, name=None, doc=None):    self.__name__ = name or func.__name__    self.__module__ = func.__module__    self.__doc__ = doc or func.__doc__    self.func = func  def __get__(self, obj, type=None):    if obj is None:      return self    value = obj.__dict__.get(self.__name__, _missing)    if value is _missing:      value = self.func(obj)      obj.__dict__[self.__name__] = value    return valueclass Foo(object):  @cached_property  def foo(self):    print 'first calculate'    result = 'this is result'    return resultf = Foo()print f.foo  # first calculate this is resultprint f.foo  # this is result

The running result shows that first calculate caches the result only after it is computed during the first call. The advantage of this is that in network programming, the parsing of the HTTP protocol usually parses the HTTP header into a dictionary of python, while in the view function, you may not know how to access this header once. Therefore, using the descriptor to cache this header can reduce unnecessary parsing.

The descriptor is widely used in python and is usually used together with the annotator. Powerful magic comes from powerful responsibility. The descriptor can also be used to "pre-compile" SQL statements in the ORM ". The proper use of descriptors can make your Python code more elegant.

Related Article

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.