写在前面
多态就是多种状态,美其名曰变态!程序在运行的过程中,根据传递的参数的不同,执行不同的函数或者操作不同的代码,这种在运行过程中才确定调用的方式成为运行时多态
人民医院.治疗(病人)
当治疗方法在执行的过程中,根据传递的数据的不同,在执行时调用
病人甲(人) 不同的处理代码或者处理函数,来完成治疗效果,动态处理(多态)
病人乙(男人)
病人丙(女人) 人的类型 VS 动物类型,不是多态~而是通过if条件判断执行代码
病人丁(动物) 人/男人/女人,执行的代码一致【运行过程中,才确定调用谁的方法】
# 定义一个人的类型
class Person:
# name姓名 age年龄 health健康值【0~50极度虚弱,51~70亚健康,71~85健康,86~100强壮】
def __init__(self, name, age, health):
self.name = name
self.age = age
self.health = health
# 康复的方法
def recure(self):
print("[%s]康复了,当前健康值%s" % (self.name, self.health))
class Man(Person):
def __init__(self, name, age, health):
Person.__init__(self,name, age, health)
def recure(self):
print("%s哇咔咔,康复了" % self.name)
class Women(Person):
def __init__(self, name, age, health):
Person.__init__(self,name, age, health)
def recure(self):
print("[%s]死鬼,终于康复了..." % self.name)
class Animal:
# name姓名 age年龄 health健康值【0~50极度虚弱,51~70亚健康,71~85健康,86~100强壮】
def __init__(self, name, age, health):
self.name = name
self.age = age
self.health = health
# 康复的方法
def recure(self):
print("[%s]嘿嘿嘿,终于康复了,当前健康值%s" % (self.name, self.health))
# 定义人民医院
class Hospital:
def __init__(self):
self.name = "人民医院"
def care(self, person):
# 类型判断,判断变量person是否Person类型
if isinstance(person, Person):
if person.health > 0 and person.health <= 50:
print("手术......")
person.health += 30
person.recure()
elif person.health > 50 and person.health <= 70:
print("输液......")
person.health += 15
person.recure()
else:
print("健康")
else:
print("不好意思,请出门左转,哪里是兽医院")
# 医院对象
hospital = Hospital()
# 生病的人
old_wang = Person("王先生", 58, 30)
mrs_li = Women("李夫人", 28, 56)
mr_li = Man("李先生", 30, 60)
# 调用了治疗的方法
hospital.care(old_wang)
hospital.care(mrs_li)
hospital.care(mr_li)
a = Animal("tom", 22, 10)
hospital.care(a)