什么是多态: 一类事物的多种形态这是其中的体现
比如: 动物类:猪,狗,人
多态基础
class Ani0mal:
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
def animal_speak(obj):
obj.speak()
animal_speak(pig)
animal_speak(people)
多态性: 是不同类型对象表现出不同行为的概念,是指在不考虑实力类型的情况下使用实例
好处: 1.
增加了程序的灵活性。2.
增加了程序额可扩展性。3.
做约束,约束我的子类干....
第一种方式: 用abcAbstract Base Classes
实现接口统一化,约束代码(用的比较少)
import abc
# 第一个括号中写metaclass=abc.ABCMeta
class Animal(metaclass=abc.ABCMeta):
# 第二在要约束的方法是,写@abc.abstractmethod装饰器
@abc.abstractmethod
def speak(self):
pass
class Pig(Animal):
def xx(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()
# animal_speak(pig)
# animal_speak(people)
pig = Pig() # 如果Pig类没有以speak定义函数,则会报错
第二种方式,用异常处理来实现(常用)
class Animal():
def speak(self):
# 主动抛出异常
raise Exception('你得给我重写他')
class Pig(Animal):
def speak(self):
print('哼哼哼')
class People(Animal):
def zz(self):
print('say hello')
pig = Pig()
pe = People()
def animal_speak(obj):
obj.speak()
animal_speak(pig)
animal_speak(pe)
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)
Linux 一切皆文件
传统方法
class File:
def read(self):
pass
def write(self):
pass
# 内存类
class Memory(File): # 内存
def read(self):
print("Memoty...read")
def write(self):
print("Memory...write")
class Netword(File): # Netword card 网卡
def read(self):
print("Netword...write")
def write(self):
print("Netword...write")
鸭子类型的写法(没有约束,自己定义,人为的)
class Memory: # 内存
def read(self):
print("Memoty...read")
def write(self):
print("Memory...write")
class Netword: # Netword card 网卡
def read(self):
print("Netword...write")
def write(self):
print("Netword...write")
def read(obj):
obj.read()
m = Memory
n = Netword
read(m)
read(n)
标签:多态性,self,多态,animal,print,class,def,speak
From: https://www.cnblogs.com/hanyingshuo/p/17797312.html