python面向对象之多态

多态

第一阶段:判断一个变量是否是某个类型可以用isinstance()判断

class Animal(object):
    def run(self):
        print("Animal is running")

class Dog(Animal):
    def run(self):
        print("Dog is running")

class Cat(Animal):
    def run(self):
        print("Cat is running")

a = list() # a是list类型
b = Animal() # b是Animal类型
c = Dog() # c是Dog类型


>>> isinstance(a, list)
True
>>> isinstance(b, Animal)
True
>>> isinstance(c, Dog)
True

阶段二:Dog是Animal的子类,那么c是否也算是Animal数据类型了?答案是肯定的,那么这个现象又说明了什么问题?

>>> isinstance(c, Animal)
True

只要子类继承自父类,子类和父类的类型相同。

阶段三:写函数,用来驱赶dog和cat,然后让dog和cat跑起来,应该如何做?

# 正常的情况下:

class Animal(object):
    def run(self):
        print("Animal is running")

class Dog(Animal):
    def run(self):
        print("Dog is running")

class Cat(Animal):
    def run(self):
        print("Cat is running")

        
def testDrive_out_dog(dog):
    print("驱赶dog")
    dog.run()
    
def Drive_out_cat(cat):
    print("驱赶cat")
    cat.run()

testDrive_out_dog(Dog())
Drive_out_cat(Cat())

第四阶段:对于上面的方法**,如果我有一万种动物需要驱赶,难道我也要写一万个驱赶函数吗?NO

class Animal(object):
    def run(self):
        print("Animal is running")

class Dog(Animal):
    def run(self):
        print("Dog is running")

class Cat(Animal):
    def run(self):
        print("Cat is running")
        
        
def Drive_out_animal(animal):
    print(f"驱赶animal")
    animal.run()
    
Drive_out_animal(Dog())	
Drive_out_animal(Cat())

其实我们只需要传入对象即可,因为dog和cat都有自己的run()方法。这就是多态。对于使用者来说,自己的代码根本无需改动,只需要拥有run()方法即可。

posted @ 2019-06-19 18:17  Hello_Jack  阅读(260)  评论(0编辑  收藏  举报
# 页脚html代码 /*头部导航栏*/ #navigator { font-size:15px; border-bottom: 1px solid #ededed; border-top: 1px solid #ededed; height: 60px;/*导航栏高度,原始50*/ clear: both; margin-top: 25px; } /*导航栏设置,可以自定义导航栏的目录*/ #navList { min-height: 35px; float: left; } #navList li { /*每一个栏目节点*/ float: left; margin: 0 5px 0 0; /*这里原来是0 40px 0 0 */ } #navList a { /*栏目文字的格式*/ display: block; width: 5em; height: 22px; float: left; text-align: center; padding-top: 19px; }