python支持多继承吗_python可以多继承吗

5d5f98ca14f88121.jpg

面向对象的主要好处就是代码的重用,实现这一特点通过继承,继承创建的新类成为子类,被继承的类称为父类。

如果在子类中需要父类的构造方法就需要显示的调用父类的构造方法,在调用基类的方法时,需要加上基类的类名前缀,且需要带上 self 参数变量。

下面我们开始来讲解继承和多继承

首先我们创建两个类,

父类:Father类 子类:Child

父类中属性为money,和一个方法play(),输出

father play with me

来表示继承父类的方法。在继承的时候我们需要在子类中导入父类

父类的代码如下:class Father(object):

def __init__(self,money):

self.money=money

print('money',money)

def play(self):

print('father play with me')

因为孩子是继承父亲的,所以孩子类中也有money属性。 所以我们直接用child来继承Father类。

child代码如下:from Father import Father

class Child(Mother,Father):

def __init__(self,money):

Father.__init__(self, money)

这个时候我们的child类就继承来自父类的属性 money 而且我们还继承了来自父类的方法play(),我们可以直接调用。

来验证一下from Child import Child

def main():

c=Child(100)

c.play()

if __name__=='__main__':

main()

我们从输出台可以得到 money 100 father play with me

多继承

单继承有时候可能满足不了我们所需的所以我们就会遇到多继承,这个同样能够展示出代码的重用。

同样是上边的例子,child不仅仅是继承来自父亲,还继承来自母亲。所以我们创建mother类class Mother(object):

def __init__(self,face):

self.face=face

print('face',face)

def play(self):

print('mother go shopping with me')

mothe类创建的属性为face,其次我们还定义的一个相同的方法play 是为了展示多继承中如果有相同的函数会调用哪个。

然后我们重写一下child类from Father import Father

from Mother import Mother

class Child(Mother,Father):

def __init__(self,money,face):

Father.__init__(self, money)

Mother.__init__(self,face)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值