How to understand Python's descriptor?

Source: Internet
Author: User
Can someone explain Python's descriptor knowledge?

Reply content:

Old article handling:

>>> class MyInt(int): ...     def Square( Self): ...             return  Self* Self ...      >>> N = MyInt(2) >>> N.name = ' both ' >>> N.Square() 4 >>> N.name ' both ' 

In a nutshell, a descriptor is a Python object, but this object is special, especially because its properties are not accessed as normal objects, and are accessed through a method called descriptor protocol. These methods include __get__, __set__, __delete__. An object that defines any of these methods is called a descriptor. As an example:


Normal Object

class Parent(object):    name = 'p'class Person(Parent):    name = "zs"zhangsan = Person()zhangsan.name = "zhangsan"print zhangsan.name#>> zhangsan
I think it is the new addition of the Python3.4 function, but also with the single-inheritance link up. Scared me to flip through the document.

Descriptor is a class of objects that implement the __get__ (), __set__ (), __delete__ () methods. It's gone. That's it. Do not read the words to learn duck typing.

It's a lot of use. The function is packaged into a property, the property is packaged into private property and so on. Image python decorator syntax, foo function is decorated, is no longer the original function,
@logger is Foo=logger (foo) 's Grammatical sugar,
Foo is the return value of Logger (foo) Inner,inner is a function, Foo (5)
equals inner (5). The formal parameter of the inner function is a variable length parameter *args,**kwargs,
Whatever you want, you can send data in the form of a tuple or a dictionary.

Two humble articles, entry level

Concise Python Magic -1
Concise Python Magic -2
  • 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.