Attribute Lookup: 当访问实例的属性时,发生了什么

原文地址, 拒绝转载: https://www.jianshu.com/p/b2691cf186d4

Attribute Lookup

假设 Cls 是类,instance 是类 Cls 的一个实例,当调用 instance.attr 时,到底发生了什么呢?下面就来一一探讨属性访问的调用流程

1 descriptor

什么是 desciptor, 官方文档给出的回答是

A descriptor is what we call any object that defines __get__(), __set__(), or __delete__().

即包含了任意 __get__ 或者 __set__ 或者 __delete__ 函数的方法的 object 都是 descriptor

2 data descriptor 与 non-data descriptors

If an object defines __set__() or __delete__(), it is considered a data descriptor. Descriptors that only define __get__() are called non-data descriptors (they are typically used for methods but other uses are possible).

如果一个 descriptor 只定义了 __get__ 方法,那么就是 non-data descriptor

如果一个 object 定义了 __set__ 或者 __delete__ 方法,那么就是 data descriptor

class DataDescriptor:
    """
    包含了 __set__ 方法,所以这个类的实例是 data-descritptor
    """
    def __init__(self, init_value):
        self.value = init_value

    def __get__(self, instance, typ):
        return 'DataDescriptor __get__' + str(typ)

    def __set__(self, instance, value):
        print ('DataDescriptor __set__')
        self.value = value

class NonDataDescriptor:
    """
    只定义了 __get__ 方法,所以这个类的实例是 non-data descriptor
    """
    def __init__(self, init_value):
        self.value = init_value

    def __get__(self, instance, typ):
        return'NonDataDescriptor __get__' + str(typ)
3 当调用 instance.attr 时,发生了什么

假设 cls 是类,instance 是类 cls 的一个实例,当调用 instance.attr 时,调用流程如下

  • 如果在cls 或者 其基类中的 __dict__ 找到了 attr,并且 attrdata descriptor 则调用其 __get__方法,即 __dict__['attr'].__get(instance, cls)

    class Base(object):
        dd_base = DataDescriptor(0)
        ndd_base = NonDataDescriptor(0)
    
    class Derive(Base):
        dd_derive = DataDescriptor(0)
        ndd_derive = NonDataDescriptor(0)
        ndd_derive2 = NonDataDescriptor(1)
        not_descriptor_in_class = "Derive not descriptor in class"
        
        def __getattr__(self, key):
            return '__getattr__ with key %s in Derive' % key
    
    print(Base.__dict__)
    """
    {
    '__module__': '__main__', 
    'dd_base': <__main__.DataDescriptor object at 0x7fc5c5b68a58>, 
    'ndd_base': <__main__.NonDataDescriptor object at 0x7fc5c5b68a90>, 
    '__dict__': <attribute '__dict__' of 'Base' objects>, 
    '__weakref__': <attribute '__weakref__' of 'Base' objects>, 
    '__doc__': None}
    """
    print(Derive.__dict__)
    """
    {'__module__': '__main__', 
    'dd_derive': <__main__.DataDescriptor object at 0x7f9e74ac79b0>, 
    'ndd_derive': <__main__.NonDataDescriptor object at 0x7f9e74ac79e8>, 'same_name_attr': 'attr in class', 
    '__doc__': None}
    """
    b = Base()
    # 打印: DataDescriptor __get__<class '__main__.Base'>
    print(b.dd_base)
    d = Derive()
    # 打印: DataDescriptor __get__<class '__main__.Derive'>
    print(d.dd_base)
    # 打印: DataDescriptor __get__<class '__main__.Derive'>
    print(d.dd_derive)
    
    # 即使我们更改了 instance 的 __dict__ 属性,访问时仍然从 data descriptor 中读取
    # 不会从 instance.__dict__ 中读取
    b.__dict__['dd_base'] = 'changed in dict dd base'
    # 打印: DataDescriptor __get__<class '__main__.Base'>
    print(b.dd_base)
    d.__dict__['dd_derive'] = 'changed in dict dd derive'
    # 打印: DataDescriptor __get__<class '__main__.Derive'>
    print(d.dd_derive)
    
    
  • 如果 attr 出现在 instance.__dict__ 中,则返回 instance.__dict__['attr']。否则,执行下面的流程

    # 更改了 instance 的 __dict__
    # 如果访问的不是 data descriptor, 则直接中 instance.__dict__ 中读取 attr
    b.__dict__['ndd_base'] = 'changed in dict ndd base'
    # 打印: changed in dict ndd base
    print(b.ndd_base)
    d.__dict__['ndd_derive'] = 'changed in dict ndd derive'
    # 打印: changed in dict ndd derive
    print(d.ndd_derive)
    
  • 如果 attr 出现在类或者基类的 __dict__

    • 如果是 non-data descriptor, 则调用 __get__方法

      # 打印: NonDataDescriptor __get__<class '__main__.Derive'>
      print(d.ndd_derive2)
      
    • 如果不是 descriptor , 则返回 __dict__['attr']

      # 打印: Derive not descriptor in class
      print(d.not_descriptor_in_class)
      
  • 如果仍未找到,如果类或者其基类有 __getattr__ 方法,则调用 __getattr__ 方法

    # 打印: __getattr__ with key no_exist_key in Derive
    print(d.no_exist_key)
    
  • 否则抛出 AttributeError

    try:
        b.no_exists_key
    except Exception as e:
        # 打印: True
        print(isinstance(e, AttributeError))
    
4 完整测试代码
class DataDescriptor:
    """
    包含了 __set__ 方法,所以这个类的实例是 data-descritptor
    """

    def __init__(self, init_value):
        self.value = init_value

    def __get__(self, instance, typ):
        return 'DataDescriptor __get__' + str(typ)

    def __set__(self, instance, value):
        print('DataDescriptor __set__')
        self.value = value


class NonDataDescriptor:
    """
    只定义了 __get__ 方法,所以这个类的实例是 non-data descriptor
    """

    def __init__(self, init_value):
        self.value = init_value

    def __get__(self, instance, typ):
        return 'NonDataDescriptor __get__' + str(typ)


class Base(object):
    dd_base = DataDescriptor(0)
    ndd_base = NonDataDescriptor(0)


class Derive(Base):
    dd_derive = DataDescriptor(0)
    ndd_derive = NonDataDescriptor(0)
    ndd_derive2 = NonDataDescriptor(1)
    not_descriptor_in_class = "Derive not descriptor in class"

    def __getattr__(self, key):
        return '__getattr__ with key %s in Derive' % key


if __name__ == '__main__':
    b = Base()
    # 打印: DataDescriptor __get__<class '__main__.Base'>
    print(b.dd_base)
    d = Derive()
    # 打印: DataDescriptor __get__<class '__main__.Derive'>
    print(d.dd_base)
    # 打印: DataDescriptor __get__<class '__main__.Derive'>
    print(d.dd_derive)

    # 即使我们更改了 instance 的 __dict__ 属性,访问时仍然从 data descriptor 中读取
    # 不会从 instance.__dict__ 中读取
    b.__dict__['dd_base'] = 'changed in dict dd base'
    # 打印: DataDescriptor __get__<class '__main__.Base'>
    print(b.dd_base)
    d.__dict__['dd_derive'] = 'changed in dict dd derive'
    # 打印: DataDescriptor __get__<class '__main__.Derive'>
    print(d.dd_derive)

    # 更改了 instance 的 __dict__
    # 如果访问的不是 data descriptor, 则直接中 instance.__dict__ 中读取 attr
    b.__dict__['ndd_base'] = 'changed in dict ndd base'
    # 打印: changed in dict ndd base
    print(b.ndd_base)
    d.__dict__['ndd_derive'] = 'changed in dict ndd derive'
    # 打印: changed in dict ndd derive
    print(d.ndd_derive)

    # 打印: NonDataDescriptor __get__<class '__main__.Derive'>
    print(d.ndd_derive2)
    # 打印: Derive not descriptor in class
    print(d.not_descriptor_in_class)

    # 打印: __getattr__ with key no_exist_key
    print(d.no_exist_key)

    try:
        b.no_exists_key
    except Exception as e:
        # 打印: True
        print(isinstance(e, AttributeError))
5 参考链接

https://blog.peterlamut.com/2018/11/04/python-attribute-lookup-explained-in-detail/
https://docs.python.org/3/howto/descriptor.html
https://www.cnblogs.com/xybaby/p/6270551.html

6 转载一下调用流程图片

图片是从参考链接的第一个博客中复制的,把调用的流程描述的很清晰,值得一看


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,607评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,239评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,960评论 0 355
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,750评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,764评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,604评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,347评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,253评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,702评论 1 315
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,893评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,015评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,734评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,352评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,934评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,052评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,216评论 3 371
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,969评论 2 355