python培训之可以多继承吗

发布时间:2022-11-16 14:06:03 人气:129 作者:多测师

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

  如果在子类中需要父类的构造方法就需要显示的调用父类的构造方法,在调用基类的方法时,需要加上基类的类名前缀,且需要带上 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类。

python培训之可以多继承吗

  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)

  以上内容为大家介绍了Python培训之可以多继承吗,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注多测师。https://www.e70w.com/xwzx/


返回列表
在线客服
联系方式

热线电话

17727591462

上班时间

周一到周五

二维码
线