python继承的特性分析

说明

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:00开始学习')


#子类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('-数据结构与算法')


#子类MathStudent继承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基础教程

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。