Python是面向对象的编程语言,也支持类继承。
>>> class Base:
... pass
...
>>> class Derived(Base):
... pass
这样就定义了两个类,Derived继承了Base。issubclass(a,b)可以测试继承关系:
>>> issubclass(Derived, Base)
True
在Python中,每个类有一个__bases__属性,列出其基类
>>> Derived.__bases__
(<class '__main__.Base'>,)
同C++,Python支持多重继承;
>>> class Derived2(Derived,Base):
... pass
...
Derived2继承了Derived和Base(实际中不会这么写)
>>> Derived2.__bases__
(<class '__main__.Derived'>, <class '__main__.Base'>)
这里,Derived,和Base的顺序不能搞反
>>> class Derived2(Base, Derived):
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Cannot create a consistent method resolution
order (MRO) for bases Derived, Base
插一段C++
C++代码 |
class Base{ };
class Derived: public Base{ };
class Derived2: public Base, public Derived{ };
int main(){ } |
mulit_inherit.cc:7:7: warning: direct base 'Base' inaccessible in 'Derived2' due to ambiguity [enabled by default] class Derived2: public Base, public Derived{ ^ |
mulit_inherit.cc:7:7: warning: direct base 'Base' inaccessible in 'Derived2' due to ambiguity [enabled by default] class Derived2: public Derived, public Base{ ^ |
可以见,C++并没有限制书写顺序。warning指示了Derrived2中不能访问Base
Derived2 d;
Base &b = d;