""" 继承的多态 """ __author__ = 'shaozhiqi' # -----------------父类------------------------ class Animal(object): def run(self): print('Animal is running...') # -----------------子类------------------------ class Dog(Animal): pass # ------------------子类---------------------------------------- class Cat(Animal): pass # -------------------子类实例------------------------------------- dog = Dog() dog.run() # Animal is running... cat = Cat() cat.run() # Animal is running... # --------------------重新定义dog 有自己的run方法------------------- class Dog(Animal): def run(self): print('Dog is running...') def eat(self): print('Dog eating meat...') dog = Dog() dog.run() # Dog is running... dog.eat() # Dog eating meat... # 当子类和父类都存在相同的run()方法时,我们说,子类的run()覆盖了父类的run(),在代码运行的时候,总是会调用子类的run()。 # 这样,我们就获得了继承的另一个好处:多态。 # 子类,那它的数据类型也可以被看做是父类。但是,反过来就不行: print(isinstance(dog, Dog)) # True print(isinstance(dog, Animal)) # True a = Animal() print(isinstance(a, Dog)) # False # -----------------------------适配---------------------------------- def run_selfrun(animal): animal.run() run_selfrun(a) # Animal is running... run_selfrun(dog) # Dog is running... # 新增一个Animal的子类,run_selfrun()不需要对做任何修改,这种方法在业务中就可以向上提取, # 实际上,任何依赖Animal作为参数的函数或者方法都可以不加修改地正常运行,原因就在于多态。 # 开闭原则: # 对扩展开放:允许新增Animal子类; # 对修改封闭:不需要修改依赖Animal类型的run_selfrun()等函数。