zoukankan      html  css  js  c++  java
  • Python中abc

    import abc
    
    指定metaclass属性将类设置为抽象类,抽象类本身只是用来约束子类的,不能被实例化
    class Animal(metaclass=abc.ABCMeta):  # 统一所有子类的方法
        @abc.abstractmethod     # 该装饰器限制子类必须定义有一个名为talk的方法
        def say(self):
            print('动物基本的发声...', end='')
    
    
    class People(Animal):   # 但凡继承Animal的子类都必须遵循Animal规定的标准
        pass
    
    
    class Dog(Animal):
        pass
    
    
    class Pig(Animal):
        pass
    
    
    obj1 = People()
    obj2 = Dog()
    obj3 = Pig()
    
    obj1.say()  # 动物基本的发声...卧槽
    obj2.say()  # 动物基本的发声...汪汪汪
    obj3.say()  # 动物基本的发声...吼吼吼
    
    # 若子类中没有一个名为talk的方法则会抛出异常TypeError,无法实例化
    # TypeError: Can't instantiate abstract class People with abstract methods say
    
    class Animal(metaclass=abc.ABCMeta):  # 统一所有子类的方法
        @abc.abstractmethod
        def say(self):
            print('动物基本的发声...', end='')
    
    
    class People(Animal):
        def say(self):
            super().say()
            print('卧槽')
    
    
    class Dog(Animal):
        def say(self):
            super().say()
            print('汪汪汪')
    
    
    class Pig(Animal):
        def say(self):
            super().say()
            print('吼吼吼')
    
    
    obj1 = People()
    obj2 = Dog()
    obj3 = Pig()
    
    obj1.say()  # 动物基本的发声...卧槽
    obj2.say()  # 动物基本的发声...汪汪汪
    obj3.say()  # 动物基本的发声...吼吼吼
    

    补充说明
    Python语言特性 - 鸭子类型
    “当一只鸟走起来像鸭子、游泳起来像鸭子、叫起来也像鸭子,那么这只鸟就可以被称为鸭子”

  • 相关阅读:
    基于jQuery的一个弹出层
    获取一个数组内的最大最小值
    flex内根据id(string)获取对象
    整理的一份iframe编辑器代码
    仿163邮箱工具条
    获取dom到浏览器窗口坐上坐标
    the solution to fix 'Failed to access IIS metabase'
    .Net下的Windows服务程序开发指南.
    Castle学习笔记之Windsor(二)
    IOC:主要概念
  • 原文地址:https://www.cnblogs.com/linqiaobao/p/13285731.html
Copyright © 2011-2022 走看看