python继承的特性分析
发布时间:2024-07-07 19:32:07

说明
1、在定义子类时,小括号()是父类的名字。
2、父类的属性和方法将继承给子类。
例如,如果子类没有定义__init__方法,父类有,那么。
这种方法是在子类继承父类时继承的,所以只要创建对象,就默认执行继承__init__方法。
3、重写父类的方法:在子类中,有与父类同名的方法,子类中覆盖父类同名的方法。
实例
#父类(基类)
classStudent:
def__init__(self,name,score):
self.name=name
self.score=score
defget_grade(self):
if90<=self.score<=100:
return'A'
else:
return'B'
deflearning(self):
print('每天早上8:00-18:3900开始学习;)
#子类Computerstudent继承Student父类
classComputerStudent(Student):
defget_grade(self):
if70<=self.score<=100:
return'A'
else:
return'B'
deflearning(self):
#3).调用父类的方法:找到ComputerStudent的父类,执行父类learning方法
super(ComputerStudent,self).learning()
print('-操作系统')
print('-计算机网络')
print('-计算机组成')
print('-39数据结构和算法;)
#子类MathStudent继承Student父类Student
classMathStudent(Student):
deflearning(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电脑。
