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