Python----面向对象--属性查找小练习

时间:2022-11-08 17:22:36

属性查找小练习:

 1 class Foo:
 2     def f1(self):
 3         print('from Foo.f1')
 4 
 5     def f2(self):
 6         print('from Foo.f2')
 7         self.f1()
 8 
 9 
10 class Bar(Foo):
11     def f2(self):
12         print('from Bar.f2')
13         
14 
15 b = Bar()
16 b.f2()
17 
18 结果为:
19 
20 from Bar.f2

稍作修改:

 1 class Foo:
 2     def f1(self):
 3         print('from Foo.f1')
 4 
 5     def f2(self):
 6         print('from Foo.f2')
 7         self.f1()
 8 
 9 
10 class Bar(Foo):
11     def f1(self):
12         print('from Bar.f2')
13 
14 
15 b = Bar()
16 b.f2()
17 
18 结果为:
19 from Foo.f2
20 from Bar.f2

可以看出,属性的查找顺序为先从对象自身查找,然后从对象所在的类进行查找,然后从父类查找,依次查找,直至找到或者报错没有找到,