How to Understand Python's Descriptor?

Source: Internet
Author: User
Can someone explain python's Descriptor knowledge? 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 = 'two' >>> n.square() 4 >>> n.name 'two' 

In short, a descriptor is a Python object, but this object is special in itsAttributeIs no longer accessed as a normal object, it is accessed through a method called descriptor protocol. These methods include _ get _, _ set _, and _ delete __. The Object Defining any method is called a descriptor. For example:


Common Object

class Parent(object):    name = 'p'class Person(Parent):    name = "zs"zhangsan = Person()zhangsan.name = "zhangsan"print zhangsan.name#>> zhangsan
I thought it was the new awesome feature in Python3.4, and it was also linked with the single inheritance. I quickly flipped through the document.

Descriptor is a class of objects that implement the _ get _ (), _ set _ (), _ delete _ () methods. No. That's it. If you do not understand it, study duck typing.

There are a lot of purposes. Encapsulate a function into a property, and package the property into a private property. The python decorator syntax of the image. After the foo function is decorated, it is no longer the original function,
@ Logger is the syntactic sugar of foo = logger (foo,
Foo is the return value inner of logger (foo), inner is a function, foo (5)
The form parameter equal to the inner (5). inner function is the variable length parameter * args, ** kwargs,
You can upload data in the form of tuples or dictionaries.

Two Essays at the 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.