多态(polymorphism)是指同一个方法调用因为对象不一样可能会产生不一样的行为。在现实 生活中,咱们有不少例子。好比:一样是调用人的休息方法,张三的休息是睡觉,李四的休 息是玩游戏,程序员是敲代码。一样是吃饭的方法,中国人用筷子吃饭,英国人用刀叉吃 饭,印度人用手吃饭。程序员
关于多态要注意如下2点:spa
1. 多态是方法的多态,属性没有多态。code
2. 多态的存在有两个必要条件:继承、方法重写。对象
【操做】blog
#多态 class Animal: def shout(self): print('动物叫了一声') class Dog(Animal): def shout(self): print('小狗,汪汪汪!!!') class Cat(Animal): def shout(self): print('小猫,喵喵喵!!!') def animalShout(a): if isinstance(a,Animal): a.shout() #传入的对象不一样,shout方法对应的实际行为也不一样 animalShout(Cat()) animalShout(Dog())
运行结果:继承
小猫,喵喵喵!!!
小狗,汪汪汪!!!游戏