Python 类继承,__bases__, __mro__, super

本文介绍了Python中的类继承概念,包括如何使用__bases__查看基类,利用__mro__理解方法解析顺序,以及如何通过super调用父类方法。通过实例展示了多态性和super的使用,解释了在基类构造函数中调用被覆盖方法的行为。
摘要由CSDN通过智能技术生成

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;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值