• 技术文章 >Python技术 >Python基础教程

    Python对象属性的查找顺序

    小妮浅浅小妮浅浅2021-05-26 09:23:24原创2115

    1、查找顺序

    (1)类和父类字典的数据描述器

    (2)实例字典

    (3)类和父类字典中的非数据描述器

    无论类有多少个继承级别,该类对象的实例字典总是存储了所有的实例变量,这也是 super 的意义之一。

    2、实例

    def get_attribute(obj, name):
        class_definition = obj.__class__
     
        descriptor = None
        for cls in class_definition.mro():
            if name in cls.__dict__:
                descriptor = cls.__dict__[name]
                break
     
        if hasattr(descriptor, '__set__'):
            return descriptor, 'data descriptor'
     
        if name in obj.__dict__:
            return obj.__dict__[name], 'instance attribute'
     
        if descriptor is not None:
            return descriptor, 'non-data descriptor'
        else:
            raise AttributeError

    以上就是Python对象属性的查找顺序,希望对大家有所帮助。更多Python学习推荐:python教学

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python对象属性
    品易云
    上一篇:__dict__在python中的实例操作 下一篇:Python中__slots__的禁用实例

    相关文章推荐

    • python中__dict__的实例属性存储• __dict__在python中的实例操作

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网