ITPub博客

首页 > IT职业 > IT图书 > python继承的特性分析

python继承的特性分析

IT图书 作者:websurf 时间:2021-09-11 09:49:52 0 删除 编辑

说明

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

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

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

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

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

实例

# 父类(基类)
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电脑。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1499/viewspace-2829093/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-15

  • 博文量
    95
  • 访问量
    1057