zoukankan      html  css  js  c++  java
  • 多态鸭子类型

    同一种事物的多种形态

    # 多态:同一种事物的多种形态
    
    class Animal:
        def run(self):
            pass
    
    
    class People(Animal):
        def run(self):
            print("people is walking")
    
    
    class Pig(Animal):
        def run(self):
            print("pig is walking")
    
    
    class Dog(Animal):
        def run(self):
            print("dog is walking")  

    多态性

    在不考虑实例类型的情况下,直接使用实例。多态性分为静态多态性和动态多态性

    好处:1、增加了程序的灵活性(以不变应万变,不论对象千变万化,使用者都是同一种形式去调用,如func(animal))

       2、增加了程序的可扩展性(通过继承animal类创建了一个新的类,使用者无需更改自己的代码,还是用func(animal))

    # 多态:同一种事物的多种形态
    
    class Animal:
        def talk(self):
            pass
    
    
    class People(Animal):
        def talk(self):
            print("say hello")
    
    
    class Cat(Animal):
        def talk(self):
            print("mew mew")
    
    
    class Dog(Animal):
        def talk(self):
            print("woof woof")
    
    
    # 多态性:指的是可以在不考虑对象类型的情况下而直接使用对象
    people = People()
    cat = Cat()
    dog = Dog()
    
    # 动态多态性
    # people.talk()
    # cat.talk()
    # dog.talk()
    
    def func(animal):
        animal.talk()
    
    func(people)
    func(dog)
    func(cat)

    鸭子类型

    Python崇尚鸭子类型,即‘如果看起来像、叫声像而且走起路来像鸭子,那么它就是鸭子’

      

    class File:
        def read(self):
            pass
    
        def write(self):
            pass
    
    
    class Disk:
        def read(self):
            print("disk read")
    
        def write(self):
            print("disk write")
    
    
    class Text:
        def read(self):
            print("text read")
    
        def write(self):
            print("text write")
    
    
    disk = Disk()
    text = Text()
    
    disk.read()
    disk.write()
    
    text.read()
    text.write()
    

     类似于

    # 序列类型:列表list,元组tuple,字符串str
    l = list([1,2,3])
    t = tuple(("a","b"))
    s = str("hello")
    
    print(l.__len__())
    print(t.__len__())
    print(s.__len__())
    
    def len(obj):
        return obj.__len__()
    
    print(len(l))
    print(len(t))
    

      

  • 相关阅读:
    区块链的入门
    数组元素查找(查找指定元素第一次在数组中出现的索引)
    数组查表法之根据键盘录入索引,查找对应星期
    数组元素反转
    数组获取最大值
    数组的遍历
    数组操作的两个常见小问题越界和空指针
    方法重载练习比较数据是否相等
    方法之根据键盘录入的数据输出对应的乘法表
    方法之根据键盘录入的行数和列数,在控制台输出星形
  • 原文地址:https://www.cnblogs.com/fantsaymwq/p/9917412.html
Copyright © 2011-2022 走看看