Python描述器

TL;DR Descriptor是Python实现streagy模式的一种变形,它将属性的访问/修改/删除委托给了Descriptor。

Descriptor

示例代码如下:

class Descriptor(object):
    class_var = "cls"

    def __init__(self, *args, **kwargs):
        # Here the `super` is differ from python2: super(Descriptor, self)
        super().__init__(*args, **kwargs)

    def __get__(self, instance, owner):
        print("==")
        print(instance, owner)
        return None

    def __set__(self, instance, value):
        print(instance, value)

    def __delete__(self, instance):
        print(instance)
`</pre>

<pre>`class Host(object):
    desc = Descriptor()
    norm = 1
`</pre>

<pre>`host = Host()
host.desc
host.norm
`</pre>

<pre>`==
&lt;__main__.Host object at 0x7ff7dbff5d68&gt; &lt;class '__main__.Host'&gt;

1
`</pre>

<pre>`host.desc = 2
host.norm = 2
`</pre>

<pre>`&lt;__main__.Host object at 0x7ff7dbff5d68&gt; 2
`</pre>

<pre>`desc = Descriptor()
desc.__get__(None, None)
`</pre>

<pre>`==
None None