流畅的python:描述符

描述符:描述符类的实例是托管类的类属性

用于研究描述符行为的几个方法:

def cls_name(obj_or_cls):
    cls = type(obj_or_cls)
    if cls is type:
        cls = obj_or_cls
    return cls.__name__.split('.')[-1]

def display(obj):
    cls =type(obj)
    if cls is type:
        return '<class {}>'.format(obj.__name__)
    elif cls in [type(None), int]:
        return repr(obj)
    else:
        return '<{} object>'.format(cls_name(obj))

def print_args(name, *args):
    persudo_args = ','.join(display(x) for x in args)
    print('-> {}.__{}__({}))'.format(cls_name(args[0]), name, persudo_args))


class Overriding:
    """由get 和set 方法的数据描述符,也称覆盖型描述符"""

    def __get__(self, instance, owner):
        print_args('get', self, instance, owner)

    def __set__(self, instance, value):
        print_args('set', self, instance, value)


class OverridingNoGet:
    """没有get方法的数据描述符,也称覆盖型描述符"""

    def __set__(self, instance, value):
        print_args('set', self, instance, vvalue)


class NonOverriding:
    """没有set方法的非数据描述符,也称非覆盖型描述符"""

    def __get__(self, instance, owner):
        print_args('get', self, instance, owner)
class Managed:
    over = Overriding()
    over_no_get = OverridingNoGet()
    non_over = NonOverriding()

    def spam(self):
        print('-> Managed.spam({})'.format(display(self)))

覆盖型描述符,也叫数据型描述符

>>> from demo import *
>>> m = Manged()
>>> m.over #get里的参数分别对应[self]Overriding实例, [instance]Managed实例,[owner]Managed类
-> Overriding.__get__(<Overriding object>,<Managed object>,<class Managed>))
>>> Managed.over #类直接调用属性,instance的位置为None。
-> Overriding.__get__(<Overriding object>,None,<class Managed>))
>>> m.over = 7 #[self]->Overriding的实例, [instance]->Managed类的实例,[value]->设置的值[7]
-> Overriding.__set__(<Overriding object>,<Managed object>,7))
>>> m.over  #读取m.over, 还是出发__get__方法
-> Overriding.__get__(<Overriding object>,<Managed object>,<class Managed>))
>>> m.__dict__['over'] = 8  #直接通过__dict__方法设置实例属性
>>> vars(m)  #__dict__属性中已经有了over属性
{'over': 8}
>>> m.over  #但是,实现了set方法的覆盖型描述符会跳过实例属性,直接读取描述符属性
-> Overriding.__get__(<Overriding object>,<Managed object>,<class Managed>))

没有get方法的覆盖型描述符

>>> m.over_no_get #没有__get__方法,所以返回描述符实例
<demo.OverridingNoGet object at 0x7fb0fd793b70>
>>> Managed.over_no_get #直接从托管类Managed中读取描述符实例也是如此
<demo.OverridingNoGet object at 0x7fb0fd793b70>
>>> m.over_no_get = 7  #设置值时出发__set__方法
-> OverridingNoGet.__set__(<OverridingNoGet object>,<Managed object>,7))
>>> m.__dict__['over_no_get'] = 7 #通过实例的__dict__属性设置名为over_no_get的实例属性
>>> m.over_no_get #现在,实例属性会覆盖描述符,因为没有定义__get__方法
7
>>> m.over_no_get = 7  #设置属性值时还是会触发描述符的__set__方法
-> OverridingNoGet.__set__(<OverridingNoGet object>,<Managed object>,7))

非覆盖型描述符,也叫非数据描述符

>>> m.non_over  #出发描述符的__get__方法
-> NonOverriding.__get__(<NonOverriding object>,<Managed object>,<class Managed>))
>>> m.non_over = 7 #没有__set__方法,所以没有干涉赋值操作。这里设置的是实例属性
>>> m.non_over #实例属性会覆盖描述符的__get__方法
7
>>> m.__dict__
{'non_over': 7}
>>> Managed.non_over  #类的描述符依然存在
-> NonOverriding.__get__(<NonOverriding object>,None,<class Managed>))
>>> del m.non_over #删除实例属性
>>> m.__dict__
{}
>>> m.non_over #再读取m.non_over时就会出发描述符的__get__方法
-> NonOverriding.__get__(<NonOverriding object>,<Managed object>,<class Managed>))

相关推荐