寫在前面

多態(tài)就是多種狀態(tài),美其名曰變態(tài)!程序在運(yùn)行的過程中,根據(jù)傳遞的參數(shù)的不同,執(zhí)行不同的函數(shù)或者操作不同的代碼,這種在運(yùn)行過程中才確定調(diào)用的方式成為運(yùn)行時(shí)多態(tài)
人民醫(yī)院.治療(病人)
當(dāng)治療方法在執(zhí)行的過程中,根據(jù)傳遞的數(shù)據(jù)的不同,在執(zhí)行時(shí)調(diào)用
病人甲(人) 不同的處理代碼或者處理函數(shù),來完成治療效果,動(dòng)態(tài)處理(多態(tài))
病人乙(男人)
病人丙(女人) 人的類型 VS 動(dòng)物類型,不是多態(tài)~而是通過if條件判斷執(zhí)行代碼
病人丁(動(dòng)物) 人/男人/女人,執(zhí)行的代碼一致【運(yùn)行過程中,才確定調(diào)用誰的方法】
# 定義一個(gè)人的類型
class Person:
# name姓名 age年齡 health健康值【0~50極度虛弱,51~70亞健康,71~85健康,86~100強(qiáng)壯】
def __init__(self, name, age, health):
self.name = name
self.age = age
self.health = health
# 康復(fù)的方法
def recure(self):
print("[%s]康復(fù)了,當(dāng)前健康值%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哇咔咔,康復(fù)了" % self.name)
class Women(Person):
def __init__(self, name, age, health):
Person.__init__(self,name, age, health)
def recure(self):
print("[%s]死鬼,終于康復(fù)了..." % self.name)
class Animal:
# name姓名 age年齡 health健康值【0~50極度虛弱,51~70亞健康,71~85健康,86~100強(qiáng)壯】
def __init__(self, name, age, health):
self.name = name
self.age = age
self.health = health
# 康復(fù)的方法
def recure(self):
print("[%s]嘿嘿嘿,終于康復(fù)了,當(dāng)前健康值%s" % (self.name, self.health))
# 定義人民醫(yī)院
class Hospital:
def __init__(self):
self.name = "人民醫(yī)院"
def care(self, person):
# 類型判斷,判斷變量person是否Person類型
if isinstance(person, Person):
if person.health > 0 and person.health <= 50:
print("手術(shù)......")
person.health += 30
person.recure()
elif person.health > 50 and person.health <= 70:
print("輸液......")
person.health += 15
person.recure()
else:
print("健康")
else:
print("不好意思,請(qǐng)出門左轉(zhuǎn),哪里是獸醫(yī)院")
# 醫(yī)院對(duì)象
hospital = Hospital()
# 生病的人
old_wang = Person("王先生", 58, 30)
mrs_li = Women("李夫人", 28, 56)
mr_li = Man("李先生", 30, 60)
# 調(diào)用了治療的方法
hospital.care(old_wang)
hospital.care(mrs_li)
hospital.care(mr_li)
a = Animal("tom", 22, 10)
hospital.care(a)
