Maison >développement back-end >Tutoriel Python >如何理解 Python 的 Descriptor?
有人可以解释一下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里新加的什么牛逼功能,还和单继承联系起来了。吓得我赶紧翻了一下文档。