【Python】实例查找属性的顺序
2019-07-28 本文已影响0人
lndyzwdxhs
# coding: utf-8
class A(object):
a = "A.class"
def __init__(self):
self.a = "A.instance"
pass
def __getattribute__(self, item):
return "A.__getattribute__"
def __getattr__(self, item):
return "A.__getattr__"
class B(A):
a = "B.class"
def __init__(self):
super(B, self).__init__()
self.a = "B.instance"
pass
def __getattribute__(self, item):
return "B.__getattribute__"
def __getattr__(self, item):
return "B.__getattr__"
inst = B()
print inst.a
子类父类所有获取属性的方法都在时,最先调用的是当前类的
__getattribute__
方法,依次注释当前调用到的方法,查看下一个调用的方法是什么,出现的顺序如下所示:
B.__getattribute__
A.__getattribute__
B.instance
A.instance
B.class
A.class
B.__getattr__
A.__getattr__
AttributeError: 'B' object has no attribute 'a'