面向对象——多态

2017-07-28  本文已影响0人  一念之间789

多态:程序在运行的过程中,根据执行条件的不同,动态执行不同的操作代码的过程称为程序运行时多态。

多态操作,通常情况和继承相关联

class Person:
#name姓名age年龄health健康值【<50极度虚弱,<70亚健康,<85健康,<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 Woman(Person):
def init(self,name,age,health):
Person.init(self,name,age,health)

def recure(self):
    print("[%s]死鬼,我康复了·····"%self.name)

class Animal:
def init(self,name,age,health):
self.name=name
self.age=age
self.health=health

def reaure(self):
    print("%s呜呜呜,本大王终于好了"%self.name)

class Hospital:
def init(self):
self.name = "人民医院"

def care(self,person):
    #类型判断,判断变量是否为Person类型
    if isinstance(person,Person):
        if person.health > 0and 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("老王",55,35)
mrs_li= Woman("李小姐",26,56)
mr_li = Man("李先生",28,75)

hospital.care(old_wang)
hospital.care(mrs_li)
hospital.care(mr_li)

a = Animal("tom",5,25)
hospital.care(a)

Paste_Image.png
程序在运行的过程中,根据传递的参数的不同,执行不同的函数或者操作不同的代码,这种在运行过程中才确定调用的方式成为运行时多态
当治疗方法在执行的过程中,根据传递的数据的不同,在执行时调用不同的处理代码或者处理函数,来完成治疗效果,动态处理(多态)
人的类型 VS 动物类型,不是多态~而是通过if条件判断执行代码人/男人/女人,执行的代码一致【运行过程中,才确定调用谁的方法】
上一篇 下一篇

猜你喜欢

热点阅读