Home >Backend Development >Python Tutorial >如何理解 Python 的 Descriptor?

如何理解 Python 的 Descriptor?

WBOY
WBOYOriginal
2016-06-06 16:23:311306browse

有人可以解释一下python的Descriptor知识吗?

回复内容:

旧文搬运:

<code class="language-python"><span class="o">>>></span> <span class="k">class</span> <span class="nc">MyInt</span><span class="p">(</span><span class="nb">int</span><span class="p">):</span> 
<span class="o">...</span>     <span class="k">def</span> <span class="nf">square</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> 
<span class="o">...</span>             <span class="k">return</span> <span class="bp">self</span><span class="o">*</span><span class="bp">self</span> 
<span class="o">...</span>      
<span class="o">>>></span> <span class="n">n</span> <span class="o">=</span> <span class="n">MyInt</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> 
<span class="o">>>></span> <span class="n">n</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="s">'two'</span> 
<span class="o">>>></span> <span class="n">n</span><span class="o">.</span><span class="n">square</span><span class="p">()</span> 
<span class="mi">4</span> 
<span class="o">>>></span> <span class="n">n</span><span class="o">.</span><span class="n">name</span> 
<span class="s">'two'</span> 
</code>

简单来讲,描述符就是一个Python对象,但这个对象比较特殊,特殊性在于其属性的访问方式不再像普通对象那样访问,它通过一种叫描述符协议的方法来访问。这些方法包括__get__、__set__、__delete__。定义了其中任意一个方法的对象都叫描述符。举个例子:


普通对象

<code class="language-django"><span class="x">class Parent(object):</span>
<span class="x">    name = 'p'</span>

<span class="x">class Person(Parent):</span>
<span class="x">    name = "zs"</span>

<span class="x">zhangsan = Person()</span>
<span class="x">zhangsan.name = "zhangsan"</span>
<span class="x">print zhangsan.name</span>
<span class="x">#>> zhangsan</span>
</code>
以为是Python3.4里新加的什么牛逼功能,还和单继承联系起来了。吓得我赶紧翻了一下文档。

Descriptor就是一类实现了__get__(), __set__(), __delete__()方法的对象。没了。就这样了。没看懂的话去学习一下duck typing。

用途就很多了。把函数包装成property,把property包装成private property等等。 图片python装饰器语法,foo函数被装饰后,不再是原函数,
@logger是foo=logger(foo) 的语法糖,
foo是logger(foo)的返回值inner,inner是一个函数,foo(5)
等于inner(5).inner函数的形式参数是可变长度参数*args,**kwargs,
随便你传元组形式或字典形式的数据都可以。

如何理解 Python 的 Descriptor? 两篇拙文,入门级水平

简明Python魔法-1
简明Python魔法-2
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn