什么是多态: 一类事物的多种形态这是其中的体现
比如: 动物类:猪,狗,人
多态基础
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
class Animal(metaclass=abc.ABCMeta):
@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')
pig = Pig()
第二种方式,用异常处理来实现(常用)
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):
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:
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)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY