python 类的多继承 深度优先和广度优先
程序员文章站
2022-03-03 11:51:33
...
1.新式类和经典类的区里
Python 2.x中默认都是经典类,只有显式继承了object才是新式类
Python 3.x中默认都是新式类,不必显式的继承object
2.多继承
class 类名(父类1, 父类2, ...)
类体
3.深度优先
class P1:
def foo(self):
print 'p1-foo'
class P2:
def foo(self):
print 'p2-foo'
def bar(self):
print 'p2-bar'
class C1(P1, P2):
pass
class C2(P1, P2):
def bar(self):
print 'C2-bar'
class D(C1, C2):
pass
d = D()
d.foo() # 输出 p1-foo
d.bar() # 输出 p2-bar
实例d调用foo()时,搜索顺序是 D => C1 => P1 实例d调用bar()时,搜索顺序是 D => C1 => P1 => P2 经典类的搜索方式:从左到右,深度优先
4.广度优先
class P1(object):
def foo(self):
print 'p1-foo'
class P2(object):
def foo(self):
print 'p2-foo'
def bar(self):
print 'p2-bar'
class C1(P1, P2):
pass
class C2(P1, P2):
def bar(self):
print 'C2-bar'
class D(C1, C2):
pass
d = D()
d.foo() # 输出 p1-foo
d.bar() # 输出 c2-bar
实例d调用foo()时,搜索顺序是 D => C1 => C2 => P1 实例d调用bar()时,搜索顺序是 D => C1 => C2
两个概念图
4.深度优先
上一篇: 图的深度优先和广度优先