父类:BMI()
子类:ChinaBMI()
类及子类(继承)的定义、实例化、重写、调用
实现代码
class BMI(object):
def __init__(self,height,weight):#__init__为默认执行
self.BMI=weight/height**2
def printBMI(self):
print('BMI:{:.1f}'.format(self.BMI))
class ChinaBMI(BMI):
def printBMI(self): #重写printBMI,如果调用子类,则直接替代父类中的printBMI
if self.BMI < 18.5:
BMI_tpye='偏瘦'
Security='低'
elif self.BMI > 18.5 and self.BMI<23.9:
BMI_tpye='正常'
Security='平均水平'
elif self.BMI > 24 and self.BMI<26.9:
BMI_tpye='偏胖'
Security='增加'
elif self.BMI > 27 and self.BMI<29.9:
BMI_tpye='肥胖'
Security='中度增加'
else:
BMI_tpye='重度肥胖'
Security='严重增加'
print('BMI分类:'+BMI_tpye+'\n'+'相关疾病发病危险性:'+Security)#换行书写方法:'\n'
if __name__ == '__main__':
#输入值
height,weight=float(1.6),float(50)
#也可以用height=input('input:height=')
#height=float(input('input:height='))
#weight=float(input('input:weight='))
print('weight:'+str(weight)+'Kg'+'\n'+'height:'+str(height)+'m')
#调用父类并赋值
BMI_V=BMI(height,weight)
BMI_V.printBMI()
#调用子类并赋值
China_BMI=ChinaBMI(height,weight)
China_BMI.printBMI()