• 技术文章 >常见问题 >Python常见问题

    python可以多继承吗

    silencementsilencement2019-08-23 15:48:41原创4132

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

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

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

    首先我们创建两个类,

    父类:Father类 子类:Child

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

    father play with me

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

    父类的代码如下:

    1

    2

    3

    4

    5

    6

    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代码如下:

    1

    2

    3

    4

    from Father import Father

    class Child(Mother,Father):

        def __init__(self,money):

            Father.__init__(self, money)

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

    来验证一下

    1

    2

    3

    4

    5

    6

    from Child import Child

        def main():

            c=Child(100)

            c.play()

    if __name__=='__main__':

        main()

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

    多继承

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

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

    1

    2

    3

    4

    5

    6

    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类

    1

    2

    3

    4

    5

    6

    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怎么确定list是否为空

    相关文章推荐

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网