zoukankan      html  css  js  c++  java
  • 约束和自定义异常

    约束

    用来约束xx类的其派生类,保证派生类中必须编写有xxx方法,不然执行就会报错

    Python中

    语法:主动抛出异常

    可以是 raise Exception(xxx)这个其实也是可以的,但不是很专业;专业的写法: raise NotImplendError(xxx)

     1 class BaseMessage(object):
     2     def send(self):
     3         """
     4         必须继承BaseMessage,然后其中必须编写send方法。用于完成具体业务逻辑。
     5         """
     6         raise NotImplementedError(".send() 必须被重写.")
     7     # raise Exception(".send() 必须被重写.")
     8     def func(self):
     9         pass
    10     def func_1(self):
    11         pass
    12 class Foo(BaseMessage):
    13     
    14     def send(self):
    15         """这个send方法时必须要有的,因其父类约束了此方法,其他方法可有可无"""
    16         pass            
    示例

    Java和C#中

    接口,接口中不允许在方法内部写代码,只能约束继承它的类必须实现接口中定义的所有方法,一个类可以实现多个接口

    interface IFoo:  # 接口  # 方法内部不可写代码
    
        def f1(self, x1):     # 接口中的方法
        pass
    
        def f2(self, x1):     # 接口中方法
            pass
    
    
    interface IBar:    # 接口
    
        def f3(self, x1):     #接口中的方法
            pass
        
        
        def f4(self, x1):     # 接口中的方法
            pass
        
    
    class Foo(IFoo, IBar):  # 实现了2个接口,上述2个接口中的方法都要在这实现
    
        def f1(self, x1):
            pass
    
        def f2(self, x1): 
            pass
    
        def f3(self, x1): 
            pass
    
        def f4(self, x1): 
            pass     
    示例

    抽象类和抽象方法约束

    需要引入库abc中ABCmeta类和abstractmethod类

    定义:

    抽象类:class 类(metaclass = ABCMeta)或__metaclass__ = ABCMeta

    抽象方法:方法上方加@abstractmethod装饰器

    from abc import ABCMeta,abstractmethod # 引入模块
    
    class Base(metaclass=ABCMeta): # 抽象类
    
        def f1(self):
            print(123)
    
    
        @abstractmethod
        def f2(self):   # 抽象方法
            pass
    
    class Foo(Base): 
    
        def f2(self):    # 必须要有
            print(666)
    示例

    应用场景:多个类,内部都必须有某些方法时,需要是有基类+异常进行约束

    自定义异常处理

    定义异常类+主动抛出异常+捕获异常

     1  # 自定义异常类
     2 class MyException(Exception):
     3     def __init__(self, code, msg):
     4         self.code = code
     5         self.msg = msg
     6 
     7 try:
     8     # 主动抛出异常 
     9     raise MyException(1000, '操作异常')
    10 
    11 except KeyError as obj:
    12     print(obj, 1111)
    13 except MyException as obj:  # 捕获异常 
    14     print(obj, 2222)
    15 except Exception as obj:
    16     print(obj, 3333)
    View Code
     1 import os
     2 
     3 class ExistsError(Exception):
     4     pass
     5 
     6 class KeyInvalidError(Exception):
     7     pass
     8 
     9 def new_func(path,prev):
    10     """
    11     去path路径的文件中,找到前缀为prev的一行数据,获取数据并返回给调用者。
    12         1000,成功
    13         1001,文件不存在
    14         1002,关键字为空
    15         1003,未知错误
    16         ...
    17     :return:
    18     """
    19     response = {'code':1000,'data':None}
    20     try:
    21         if not os.path.exists(path):
    22             raise ExistsError()    #  主动抛出异常1
    23 
    24         if not prev:
    25             raise KeyInvalidError()  # 主动抛出异常2
    26         pass
    27     except ExistsError as e:        # 捕捉异常
    28         response['code'] = 1001
    29         response['data'] = '文件不存在'
    30     except KeyInvalidError as e:
    31         response['code'] = 1002
    32         response['data'] = '关键字为空'
    33     except Exception as e:
    34         response['code'] = 1003
    35         response['data'] = '未知错误'
    36     return response
    37 
    38 
    39 def func(path,prev):
    40     """
    41     去path路径的文件中,找到前缀为prev的一行数据,获取数据并返回给调用者。
    42         1000,成功
    43         1001,文件不存在
    44         1002,关键字为空
    45         1003,未知错误
    46         ...
    47     :return:
    48     """
    49     response = {'code':1000,'data':None}
    50     try:
    51         if not os.path.exists(path):
    52             response['code'] = 1001
    53             response['data'] = '文件不存在'
    54             return response
    55         if not prev:
    56             response['code'] = 1002
    57             response['data'] = '关键字为空'
    58             return response
    59         pass
    60     except Exception as e:
    61         response['code'] = 1003
    62         response['data'] = '未知错误'
    63     return response
    练习
  • 相关阅读:
    单例模式
    HashSet、LinkedHashSet、SortedSet、TreeSet
    ArrayList、LinkedList、CopyOnWriteArrayList
    HashMap、Hashtable、LinkedHashMap
    andrew ng machine learning week8 非监督学习
    andrew ng machine learning week7 支持向量机
    andrew ng machine learning week6 机器学习算法理论
    andrew ng machine learning week5 神经网络
    andrew ng machine learning week4 神经网络
    vue组件监听属性变化watch方法报[Vue warn]: Method "watch" has type "object" in the component definition. Did you reference the function correctly?
  • 原文地址:https://www.cnblogs.com/--kai/p/9566882.html
Copyright © 2011-2022 走看看