python可以多继承吗

496次阅读
没有评论

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类。

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)
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2019-12-09发表,共计1338字。
新手QQ群:570568346,欢迎进群讨论 Python51学习
评论(没有评论)