- 属性查找顺序:
- 首先,Python会在实例对象的
__dict__
中查找该属性。如果找到了,就直接返回该属性的值。
- 如果在实例对象的
__dict__
中没有找到,Python会在实例的类(__class__
)的 __dict__
中查找,即查找类属性。
- 如果在类的
__dict__
中也没有找到,Python会沿着继承链向上,在父类的 __dict__
中查找,依次类推,直到找到该属性或者到达继承链的顶端(object
类,如果没有其他父类的话)。如果到达继承链顶端还没有找到,就会抛出 AttributeError
异常。
- 代码示例:
class Parent:
class_attr = 'Parent class attribute'
class Child(Parent):
def __init__(self):
self.instance_attr = 'Child instance attribute'
child = Child()
# 查找实例属性
print(child.instance_attr)
# 查找类属性
print(child.class_attr)
# 查找父类属性(这里子类没有重写,所以和类属性查找类似)
print(child.class_attr)