什么是多态,什么是多态性
多态是指一类事物的多种形态,例如:动物类(猪,狗,人...)
多态性是指在不考虑实例的情况下使用实例
多态性的好处
- 增加了程序的灵活性
- 增加了程序额可拓展性
多态基础
class Animal:
def speak(self):
pass
class Pig(Animal):
def speak(self):
print('哼哼哼')
class Dog(Animal):
def speak(self):
print('汪汪')
class People(Animal):
def speak(self):
print('say hello')
pig=Pig()
dog=Dog()
people=People()
# pig.speak()
# dog.speak()
# people.speak()
def animal_speak(obj):
obj.speak()
animal_speak(pig)
animal_speak(people)
#第一种方式:用abc实现接口统一化,约束代码(用的比较少)
import abc
#第一在括号中写metaclass=abc.ABCMeta
class Animal(metaclass=abc.ABCMeta):
#第二在要约束的方法上,写abc.abstractmethod装饰器
@abc.abstractmethod
def speak(self):
pass
class Pig(Animal):
def speak(self):
print('哼哼哼')
class Dog(Animal):
def yy(self):
print('汪汪')
class People(Animal):
def zz(self):
print('say hello')
people = People()
people.zz()
# 这样就不能利用多态性
def animal_speak(obj):
obj.speak()
pig=Pig()
#第二种方式,用异常处理来实现(常用)
class Animal():
def speak(self):
#主动抛出异常
raise Exception('你得给我重写它啊')
class Pig(Animal):
def speak(self):
print('哼哼哼')
class People(Animal):
def speak(self):
print('say hello')
pig=Pig()
pe=People()
def animal_speak(obj):
obj.speak()
animal_speak(pig)
animal_speak(pe)
python中鸭子类型
Python崇尚鸭子类型,即‘如果看起来像、叫声像而且走起路来像鸭子,那么它就是鸭子
class Pig:
def speak(self):
print('哼哼哼')
class People:
def speak(self):
print('say hello')
pig=Pig()
pe=People()
def animal_speak(obj):
obj.speak()
animal_speak(pig)
animal_speak(pe)
传统写法
class File:
def read(self):
pass
def write(self):
pass
#内存类
class Memory(File):
def read(self):
print('Memory...read')
def write(self):
print('Memory...write')
class Network(File):
def read(self):
print('Network...read')
def write(self):
print('Network...write')
鸭子类型写法
内存类
class Memory:
def read(self):
print('Memory...read')
def write(self):
print('Memory...write')
class Network:
def read(self):
print('Network...read')
def write(self):
print('Network...write')
def read(obj):
obj.read()
m=Memory()
n=Network()
read(m)
read(n)