ITPub博客

首页 > IT职业 > IT职场 > Python对象属性的查找顺序

Python对象属性的查找顺序

IT职场 作者:my420 时间:2021-09-11 09:57:59 0 删除 编辑

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电脑。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/406/viewspace-2830402/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2020-07-23

  • 博文量
    0
  • 访问量
    478