Python 父子类继承笔记

来源:互联网 发布:足球数据分析软件 编辑:程序博客网 时间:2024/05/29 13:20

单项继承

简介:继承者含有被继承者的所有属性方法或函数。
例如:

class Parent:    def hello(self):        print("父类方法")class Child(Parent):    pass     # python有自己的语法标准,当我希望类是空实现的时候。    # 是不符合python的语法标准的,所以不能通过编译,    # 但我通过pass关键字显式的告诉解释器,这里是空实现。a = Parent()a.hello()b = Child()b.hello()

Child内虽然只有pass,但它包含了Parent的所有函数。所以a.hello()和b.hello()运行会显示相同效果。
效果如下:

a = Parent()a.hello()父类方法b = Child()b.hello()父类方法

如果子类的函数名于父类的函数名冲突,那么子类的函数会覆盖父类的同名函数。
例如:

class Parent:    def hello(self):        print("父类方法")class Child(Parent):    def hello(self):        print("子类方法")b = Child()b.hello()

这里的b.hello()会显示子类方法。

b = Child()b.hello()子类方法

若父子类含有同名函数且想要实现父类的函数,那么就有两种方法解决。
1,调用未绑定的父类方法

class Parent:    def hello(self):        print("父类方法")class Child(Parent):    def hello(self):        Parent.hello(self) #只需要把需要的父类的函数加到子类中就行        print("子类方法")b = Child()b.hello()

效果如下:

b = Child()b.hello()父类方法

2,使用super函数
简介:自动找到基类(父类)的方法并传入参数。

class Parent:    def hello(self):        print("父类方法")class Child(Parent):    def hello(self):        super().hello()  #添加函数super自动寻找基类的函数并传入参数        print("子类方法")b = Child()b.hello()

效果如下

b = Child()b.hello()父类方法

多重继承

简介:子类同时继承多个父类的属性。

class A:    def A1(self):        print("我代表A")class B:    def B1(self):        print("我代表B")class C(A, B):    passc = C()c.A1()c.B1()

效果如下:

c.A1()我代表Ac.B1()我代表B

注:多重函数虽然功能强大,但是容错率极低。故不到万不得已,就不要用多重函数!

阅读全文
2 0
原创粉丝点击