Python——多态 发表于 2018-11-05 | 分类于 Python入门 | | 阅读数 字数统计: 344 | 阅读时长 ≈ 1 多态什么是多态?多态指的是同一种事物多种形态 为何要用多态?用基类创建一套规则,强制子类去遵循,这样便可以再不用考虑对象具体类型的前提下而直接使用对象下的方法 如何用多态?123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960class Animal: def eat(self): pass def drink(self): pass def bark(self): passclass Cat(Animal): def bark(self): print('喵喵喵')class Dog(Animal): def bark(self): print('汪汪汪')c = Cat()d = Dog()# 可以在不考虑对象具体类型的前提下而直接使用对象下的方法# 规则强制import abc #abstract classclass Animal(metaclass=abc.ABCMeta): @abc.abstractmethod def eat(self): pass @abc.abstractmethod def drink(self): pass @abc.abstractmethod def bark(self): pass# obj=Animal() # 抽象基类本身不能被实例化class Cat(Animal): def eat(self): print('cat eat') def drink(self): print('cat drink') def bark(self): print('喵喵喵')class Dog(Animal): def eat(self): print('dog eat') def drink(self): print('dog drink') def bark(self): print('汪汪汪')def BARK(animal): animal.bark()c = Cat()c.bark()BARK(c) 鸭子类型123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960class Foo: def f1(self): print('from foo.f1') def f2(self): print('from foo.f2')class Bar: def f1(self): print('from bar.f1') def f2(self): print('from bar.f2')obj1=Foo()obj2=Bar()obj1.f1()obj1.f2()obj2.f1()obj2.f2()class Disk: def read(self): print('disk read') def write(self): print('disk write')class Txt: def read(self): print('txt read') def write(self): print('txt write')class Process: def read(self): print('process read') def write(self): print('process write')obj1=Disk()obj2=Txt()obj3=Process()obj1.read()obj2.read()obj3.read()