A concise guide to using descriptor descriptors in Python

Source: Internet
Author: User
Descriptor is primarily used to define methods and properties in Python and is quite tricky to use, so let's start with the basics and sort out a brief guide to using the descriptor descriptor in Python

When defining iterators, the description is the object that implements the iterative protocol, the object that implements the __iter__ method. Similarly, the so-called descriptor, which implements the descriptor protocol, is the object of the __get__, __set__, and __delete__ methods.

Look at the definition alone, or rather abstract. Talk is cheap. Look at 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): C6/>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 descriptor protocols __get__ and __SET__, which is a descriptor (the class is also an object and everything is an object). At the same time implement __get__ and __set__ called Data Descriptor (data descriptor). The only implementation of __GET__ is a non-descriptor. The difference between the two is the precedence of the dictionary relative to the instance.

If the instance dictionary has a property with the same name as the descriptor, if the descriptor is a data descriptor, the data descriptor is preferred, and if it is a non-data descriptor, the attributes in the dictionary are preferred.

Invocation of the Descriptor
For this kind of magic, the calling method is often not used directly. For example, adorners need to be called with the @ symbol. Iterators are usually called in an iterative process, or by using the next method. The descriptor is relatively simple and is called when the object's properties are.

In [all]: Webframework = Webframework () in [+]: webframework.__get__ (webframework, Webframework) out[16]: ' Flask '

Application of descriptors
The role of descriptors is primarily defined by methods and properties. Now that we can re-describe the properties of the class, this magic can change some of the behavior of the class. The simplest application is the ability to write a cache of class properties in conjunction with adorners. The author of Flask wrote a library of Werkzeug Web tools, which uses the descriptors feature 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 was None:      return self    value = OBJ.__DICT__.G ET (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 was result '    return RESULTF = Foo () print F.foo  # First calculate this is Resultprint F.foo
  # This is result

The results of the operation are visible, and first calculate is cached only after it has been evaluated at the time of the initial call. The advantage is that in network programming, the parsing of the HTTP protocol, usually the HTTP header parsing into a Python dictionary, while in the view function, may not know the first time to access the header, so the header using the descriptor cache, Can reduce the redundant parsing.

Descriptors are widely used in Python, often in conjunction with adorners. Powerful magic comes from a strong responsibility. The descriptor can also be used to implement the "precompilation" of SQL statements in ORM. The proper use of descriptors can make your Python code more elegant.

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.