code1:
class base(object):
def test(self):
pass
class low1(object):
def test(self):
super(low1, self).test()
print "low1 test"
class low2(object):
def test(self):
super(low2, self).test()
print "low2 test"
class high(low1, low2, base):
pass
if __name__ == "__main__":
high().test()
代码 2:
class base(object):
def test(self):
pass
class low1(object):
def test(self):
# super(low1, self).test()
print "low1 test"
class low2(object):
def test(self):
# super(low2, self).test()
print "low2 test"
class high(low1, low2, base):
pass
if __name__ == "__main__":
high().test()
Code1 的输出为:
low2 test
low1 test
Code2 的输出为:
low1 test
当我调用为什么高对象的测试方法时,它会同时执行 low1 和 low2 的测试方法?
看看方法解析顺序:
print(high.mro())
这将打印:
[<class '__main__.high'>, <class '__main__.low1'>, <class '__main__.low2'>,
<class '__main__.base'>, <class 'object'>]
想想super()
意思是"下一个行",其中行是上面显示的类列表。因此,super(low1, self)
发现low2
是下一个班级。