zoukankan      html  css  js  c++  java
  • python note 25 约束

    1、约束

    class BaseMessage(object):
        def send(self):
            """
            必须继承BaseMessage,然后其中必须编写send方法。用于完成具体业务逻辑。
            """
            raise NotImplementedError(".send() 必须被重写.") #主动抛异常
            # raise Exception(".send() 必须被重写.")
    
    
    # BaseMessage类用于约束,约束其派生类:保证派生类中必须编写send方法,不然执行可能就会报错。

    例子

    class BaseMessage(object):
        def send(self):
            """
            必须继承BaseMessage,然后其中必须编写send方法。用于完成具体业务逻辑。
            """
            raise Exception()
    
    class Email(BaseMessage):
        def send(self):
            pass  # 发送邮件
    
        def f1(self):
            pass
    
        def f2(self):
            pass
    
    class Wechat(BaseMessage):
        def send(self):
            pass  # 发送微信
    
        def f1(self):
            pass
    
        def f2(self):
            pass
    
    class Msg(BaseMessage):
        def send(self):
            pass  # 发送短信
    
        def f1(self):
            pass
    
        def f2(self):
            pass 

    2、结论

    1.
    什么是接口以及作用?
    接口时一种数据类型,主要用于约束派生类中必须实现指定的方法。
    Python中不存在,Java和C  # 中是存在的。
    2. Python中使用过什么来约束呢? - 抽象类 + 抽象方法,编写上麻烦。 - 人为主动抛出异常 3. 约束时,抛出的异常是否可以用其他的? 不专业:raise Exception(".send() 必须被重写.") 专业:raise NotImplementedError(".send() 必须被重写.") 4. 以后看代码,揣摩心思

    3、自定义异常

    class KeyError(Exception): #定义异常
        pass
    class MyException(Exception):
        def __init__(self, code, msg):
            self.code = code
            self.msg = msg
    try:
        raise MyException(1000, '操作异常')
    except KeyError as obj:
        print(obj, 1111)
    except MyException as obj:  # 知识点:捕获异常
        print(obj, 2222)
    except Exception as obj:
        print(obj, 3333)

    例子

    import os
    
    class ExistsError(Exception):
        pass
    
    class KeyInvalidError(Exception):
        pass
    
    def new_func(path,prev):
        """
        去path路径的文件中,找到前缀为prev的一行数据,获取数据并返回给调用者。
            1000,成功
            1001,文件不存在
            1002,关键字为空
            1003,未知错误
            ...
        :return:
        """
        response = {'code':1000,'data':None}
        try:
            if not os.path.exists(path):
                raise ExistsError()
    
            if not prev:
                raise KeyInvalidError()
            pass
        except ExistsError as e:
            response['code'] = 1001
            response['data'] = '文件不存在'
        except KeyInvalidError as e:
            response['code'] = 1002
            response['data'] = '关键字为空'
        except Exception as e:
            response['code'] = 1003
            response['data'] = '未知错误'
        return response

    4、日志

    import logging
    
    logger = logging.basicConfig(filename='xxxxxxx.txt',
                                 format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                                 datefmt='%Y-%m-%d %H:%M:%S',
                                 level=30)
    
    # logging.debug('x1') # 10
    # logging.info('x2')  # 20
    # logging.warning('x3') # 30
    # logging.error('x4')    # 40
    # logging.critical('x5') # 50
    # logging.log(10,'x6')
    
    
    import traceback
    
    def func():
        try:
            a = a +1
        except Exception as e:
            # 获取当前错误的堆栈信息
            msg = traceback.format_exc()
            logging.error(msg)
    func()
  • 相关阅读:
    金蝶k3wise 核算项目、辅助资料
    金蝶——“免、抵、退”税操作说明及帐务处理
    阿里云各Linux发行版netcore兼容性评估报告---来自大石头的测试
    金蝶KIS&K3助记码SQL数据库批量刷新
    华为交换机批量加入 Vlan 方法
    华为设备默认console密码
    SQL查询数据并插入新表
    ORACLE删除当前用户下所有的表的方法
    【转】使用Navicat for Oracle新建表空间、用户及权限赋予
    [转]spring mvc注解方式实现向导式跳转页面
  • 原文地址:https://www.cnblogs.com/P-Z-W/p/11108877.html
Copyright © 2011-2022 走看看