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)
class Host(object):
desc = Descriptor()
norm = 1
host = Host()
host.desc
host.norm
==
<__main__.Host object at 0x7ff7dbff5d68> <class '__main__.Host'>
1
host.desc = 2
host.norm = 2
<__main__.Host object at 0x7ff7dbff5d68> 2
desc = Descriptor()
desc.__get__(None, None)
==
None None