• 技术文章 >Python技术 >Python基础教程

    python继承的特性分析

    小妮浅浅小妮浅浅2021-08-23 09:33:37原创2274

    说明

    1、子类继承时,在定义类时,小括号()是父类的名字。

    2、父类的属性和方法将继承给子类。

    例如,如果子类没有定义__init__方法,父类有,那么。

    这种方法是在子类继承父类时继承的,所以只要创建对象,就默认执行了继承的__init__方法。

    3、重写父类的方法:在子类中,有与父类同名的方法,子类中的方法覆盖父类中同名的方法。

    实例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    56

    # 父类(基类)

    class Student:

        def __init__(self, name, score):

            self.name = name

            self.score = score

      

        def get_grade(self):

            if 90 <= self.score <= 100:

                return 'A'

            else:

                return 'B'

      

        def learning(self):

            print('每天早上8:00-18:00开始学习')

      

      

    # 子类ComputerStudent继承Student父类

    class ComputerStudent(Student):

        def get_grade(self):

            if 70 <= self.score <= 100:

                return 'A'

            else:

                return 'B'

      

        def learning(self):

            # 3). 调用父类的方法:找到ComputerStudent的父类,执行父类的learning方法

            super(ComputerStudent, self).learning()

            print('   - 操作系统')

            print('   - 计算机网络')

            print('   - 计算机组成')

            print('   - 数据结构与算法')

      

      

    # 子类MathStudent继承Student父类

    class MathStudent(Student):

        def learning(self):

            # 3).调用父类的方法:找到MathStudent的父类,执行父类的learning方法

            super(MathStudent, self).learning()

            print('   - 高等数学')

            print('   - 线性代数')

      

      

    # s = Student('张三', 100)

    # print(s.name, s.score, s.get_grade())

      

    # 1). 继承规则: 自己有get_grade方法执行自己的get_grade方法

    s1 = ComputerStudent('李四', 80)

    print(s1.get_grade())  # A

    s1.learning()

    # print(s1.aa())   # 不会执行

      

    # 2). 继承规则: 自己没有get_grade方法执行父类的get_grade方法

    s2 = MathStudent('张三', 80)

    print(s2.get_grade())  # B

    # print(s1.aa())   # 不会执行

    s2.learning()

    以上就是python继承的特性分析,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python继承
    上一篇:python中Pylint的信息类型 下一篇:python return和yield的执行比较

    相关文章推荐

    • python继承是如何实现的• python继承类中如何重写?• python继承是什么?• python继承的特征有哪些?• python继承的基类属性分析• Python继承的原理分析• python继承的多种类型

    全部评论我要评论

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

  • 取消发布评论
  • 

    Python学习网