多态和多态性

什么是多态: 一类事物的多种形态这是其中的体现

比如: 动物类:猪,狗,人

多态基础

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)
posted @   hanyingshuo  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示