# Python learning
# coding:utf-8
# 1.什么是多态:同一事物有多种形态
# 2.为何要有多态 ==>多态会带来什么样的特性,多态性
class Animal: # 统一所有子类的方法
def say(self):
print('动物叫:', end='')
class People(Animal):
def say(self):
super().say()
print('嘤嘤嘤')
class Dog(Animal):
def say(self):
super().say()
print('汪汪汪')
class Pig(Animal):
def say(self):
super().say()
print('哼哼哼')
obj_say1 = People()
# obj_say1.say()
obj_say2 = Dog()
# obj_say2.say()
obj_say3 = Pig()
# obj_say3.say()
# 定义统一的接口,接收传入的动物对象
def animal_say(animal):
animal.say()
animal_say(obj_say1)
animal_say(obj_say2)
animal_say(obj_say3)
# 鸭子类型
class Cpu:
def read(self):
print('cpu read')
def write(self):
print('cpu write')
class Mem:
def read(self):
print('mem read')
def write(self):
print('mem write')
class Txt:
def read(self):
print('txt read')
def write(self):
print('txt write')
obj1 = Cpu()
obj2 = Mem()
obj3 = Txt()
obj1.read()
obj1.write()
obj2.read()
obj2.write()
obj3.read()
obj3.write()