Python 多态性

1.方法的覆写:子类继承父类后可以根据父类的方法名称进行方法体的重新定义。

2.对象多态性:在方法覆写的基础上利用相同的方法名称作为标准,就可以在不考虑具体类型的情况下实现不同子类中相同方法的调用

实例:方法覆写

class Channel:
    def build(self):
        print("通道连接")
        
class DatabaseChannel(Channel):
    def build(self):
        print("数据库通道连接")


def main():
    channel=DatabaseChannel()
    channel.build()
if __name__ =="__main__":
    main()

实例:调用父类被覆写的方法

class Channel:
    def build(self):
        print("通道连接")
        
class DatabaseChannel(Channel):
    def build(self):
        super().build()
        print("数据库通道连接")


def main():
    channel=DatabaseChannel()
    channel.build()
if __name__ =="__main__":
    main()

对象的多态性:

class Message:
    def get_info(self):
        return "Message"
    
class DatabaseMessage(Message):
    def get_info(self):
        return "DatabaseMessage"
    
class NetMessage(Message):
    def get_info(self):
        return "NetMessage"
    
class Channel:
    def send(self,msg):
        print(msg.get_info())
        

def main():
    channel=Channel()
    channel.send(Message())
    channel.send(DatabaseMessage())
    channel.send(NetMessage())
    
if __name__ =="__main__":
    main()

利用isinstance()函数保证代码的正确执行

class Message:
    def get_info(self):
        return "Message"
    
class DatabaseMessage(Message):
    def get_info(self):
        return "DatabaseMessage"
    
class NetMessage(Message):
    def get_info(self):
        return "NetMessage"
    
class Channel:
    def send(self,msg):
        if isinstance(msg, DatabaseMessage):
            print(msg.get_info())
        

def main():
    channel=Channel()
    channel.send(Message())
    channel.send(DatabaseMessage())
    channel.send(NetMessage())
    
if __name__ =="__main__":
    main()

工厂设计模式

你可能感兴趣的:(python,python)