zoukankan      html  css  js  c++  java
  • 约束,自定义异常,日志

    一.约束

    约束某各类
    用于约束其派生类,保证其派生类中有send方法,不然执行可能会报错
    约束其派生类,python中用类来实现,Java和C#中用接口或类来实现
    (1) 对于Java/C#:
        类:(java和C#是先编译后运行的,所以如果不满足条件,一开始就会报错,根本无法运行)
     1     class Foo:
     2         def f1(self):
     3             pass  #可认为抛出异常
     4 
     5     抽象类:约束他的派生类必须实现他其中的抽象方法
     6     abstact class Foo:
     7         def f1(self):  #此方法可以不用继承
     8             pass
     9 
    10         abstact  def f2(self):
    11             pass
    12     class Bar:
    13         def f2(self):
    14             pass
    类:
    1 abstact class Foo:
    2         def f1(self):  #此方法可以不用继承
    3             pass
    4 
    5         abstact  def f2(self):
    6             pass
    7     class Bar:
    8         def f2(self):
    9             pass
    抽象类:约束他的派生类必须实现他其中的抽象方法
     1 interface Foo:
     2     def f1(self,x1):pass
     3 
     4     def f2(self,x1):pass
     5 
     6 interface Bar:
     7     def f3(self,x1):pass
     8 
     9     def f4(self,x1):pass
    10 
    11 class Aou(Foo,Bar):
    12     def f1(self,x1):pass
    13 
    14     def f2(self,x1):pass
    15 
    16     def f3(self,x1):pass
    17 
    18     def f4(self,x1):pass
    接口:接口中可以有多个接口

      (2)python中:

     1 class BaseMessage:
     2     def send(self):
     3         '''
     4         必须继承BaseMessage,然后其中必须编写send方法,用于完成具体的业务逻辑
     5         '''
     6         # raise Exception('...')
     7         raise NotImplementedError('send方法必须被重写')  #更专业   #NotImplementedError是没有实现的意思
     8 
     9 class Email(BaseMessage):
    10     def send(self):
    11         pass  #发送邮件
    12 
    13     def f1(self):
    14         pass
    15 
    16     def f2(self):
    17         pass
    18 
    19 class Wechat(BaseMessage):
    20     def send(self):
    21         pass
    22 
    23     def f3(self):
    24         pass
    25 
    26 class Messege(BaseMessage):
    27     def send(self):
    28         pass
    29 
    30     def f4(self):
    31         pass
    32 
    33 def func(arg):
    34     '''
    35     报警通知
    36     :param arg:
    37     :return:
    38     '''
    39     arg.send()
    类:
     1 from abc import ABCMeta,abstractmethod
     2 class Base(metaclass=ABCMeta):  #定义了一个抽象类
     3     def f1(self):
     4         print(123)
     5 
     6     @abstractmethod
     7     def f2(self):  #定义了一个抽象方法
     8         pass
     9 
    10 class Foo(Base):
    11     def f2(self):
    12         print(666)
    13 
    14 obj=Foo()
    15 obj.f1()
    16 obj.f2()
    抽象方法:(一般不用)
    总结:
    1.什么是接口,以及作用?
    接口是一种数据类型,用于约束派生类中必须实现指定方法
    python中不存在,在Java和C#中存在
    2.python中用什么来约束
    抽象方法,抽象类(编写上麻烦)
    认为主动抛出异常
    3.约束时抛出的异常是否可以用其他的
    不专业:raise Exception('...')
    专业:raise NotImplementedError('send方法必须被重写')
    4.以后看代码时,揣摩写代码的人的心思

    5.应用场景:
    多个类,内部都必须有某各类或某个方法时,需要使用基类+异常进行约束
     1 class Base:
     2     def login(self):
     3         raise NotImplementedError('...')
     4 
     5 class  Student(Base):
     6     def login(self):
     7         pass
     8     def score(self):
     9         pass
    10 
    11 class Teather(Base):
    12     def login(self):
    13         pass
    14 
    15     def exam(self):
    16         pass
    17 
    18 class Messaer(Base):
    19     def login(self):
    20         pass
    21     def set(self):
    22         pass
    学员管理系统;

    二.自定义异常

     1 import os
     2 def func(path,prev):
     3     '''
     4     去路径的文件中,找到前缀为prev的一行数据,获取数据并返回给调用者'
     5     1000 成功
     6     1001 文件不存在
     7     1002 关键字为空
     8     1003 未知错误
     9     :param path:
    10     :param prev:
    11     :return:
    12     '''
    13     response ={'code':1000,'data':None}
    14     try:
    15         if not os.path.exists(path):
    16             response['code'] = 1001
    17             response['data'] = '文件不存在'
    18             return response
    19         if not prev:
    20             response['code'] = 1002
    21             response['data'] = '关键字为空'
    22             return response
    23     except Exception as e:
    24         response['code']=1003
    25         response['data']='未知错误'
    26     return response
    27 def func2():
    28     return 8
    29 def  show():
    30     v1=func()
    31     v2=func2()
    1.业务逻辑简单时
     1 class ExistsError(Exception):  #自定义异常类,自定义的异常类要继承Exception
     2     pass
     3 class KeyInvalidError(Exception):
     4     pass
     5 import os
     6 def new_func(path,prev):
     7     '''
     8     去路径的文件中,找到前缀为prev的一行数据,获取数据并返回给调用者'
     9     1000 成功
    10     1001 文件不存在
    11     1002 关键字为空
    12     1003 未知错误
    13     '''
    14     response ={'code':1000,'data':None}
    15     try:   #目的就是为了让try中的代码简单明了
    16         if not os.path.exists(path):
    17             raise ExistsError
    18         if not prev:
    19             raise KeyInvalidError
    20     except ExistsError as e:
    21         response['code'] = 1001
    22         response['data'] = '文件不存在'
    23     except KeyInvalidError as e:
    24         response['code'] = 1002
    25         response['data'] = '关键字为空'
    26     except Exception as e:
    27         response['code']=1003
    28         response['data']='未知错误'
    29     return response
    30 def func2():
    31     return 8
    32 def  show():
    33     v1=new_func()
    34     v2=func2()
    业务逻辑复杂时
     1 class MyException(Exception):  #异常也是一个类
     2     def __init__(self,code,msg):
     3         self.code=code
     4         self.msg=msg
     5 
     6 try :  #主动抛出异常
     7     raise MyException(1000,'异常类型')
     8 
     9 except   MyException as e:  #捕获异常
    10     print(e.code,e.msg)
    自定义异常还可以这样写

    三. 加密(一些密码类的内容,如果不加密一但泄露,会造成严重的)

    import hashlib  #帮助加密的模块
    
    obj=hashlib.md5(b'6khiy78g76tfmjyvf64')
    # 写入要加加密的字节
    obj.update('admin'.encode('utf-8'))
    
    v=obj.hexdigest() #获取密文
    print(v)
      关键词:撞库 将常见的密文归纳总结,一个一个试
    加盐:obj=hashlib.md5(b'6khiy78g76tfmjyvf64')
     1 Hash objects have these methods:
     2 - update(arg): Update the hash object with the bytes in arg. Repeated calls
     3                 are equivalent to a single call with the concatenation of all
     4                 the arguments.
     5  - digest():    Return the digest of the bytes passed to the update() method
     6                 so far.
     7  - hexdigest(): Like digest() except the digest is returned as a unicode
     8                 object of double length, containing only hexadecimal digits.
     9  - copy():      Return a copy (clone) of the hash object. This can be used to
    10                 efficiently compute the digests of strings that share a common
    11                 initial substring.
    内部逻辑
     1 import hashlib
     2 mi=b'6khiy78g76tfmjyvf64'
     3 def md5(ped):
     4 
     5     obj=hashlib.md5(mi)
     6 
     7     obj.update('admin'.encode('utf-8'))
     8 
     9     return obj.hexdigest()
    10 
    11 name=input('亲输入用户名')
    12 pwd=input('亲输入用密码')
    13 
    14 if name=='ninini' and md5(pwd)=='263930cf6ae488d074e32def60d973cc':
    15     print('登录成功')
    实例

    四.日志(logging)

    为什么要有日志:
    给开发人员看,用于排查错误
    import logging
                                #路径或文件名
    logger=logging.basicConfig(filename='log.log',
                        format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S %p',
                        level=10) #用于控制日志的错误级别
    logging.debug('x1')  #10  正常测试
    logging.info('x2')  #20   正常的信息
    logging.warning('x3')  #30   警告
    logging.error('x4')  #40   错误
    logging.critical('x5')  #50   立即解决的错误
    logging.log(10,'log')
    
    def func():
        try:
            a=a+1
    
        except Exception as e:
            print(e)
            logging.error(str(e))
    func()
    日志错误处理:
    import logging
                                #路径或文件名
    logger=logging.basicConfig(filename='log.log',
                        format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S %p',
                        level=10) #用于控制日志的错误级别
    logging.debug('x1')  #10  正常测试
    logging.info('x2')  #20   正常的信息
    logging.warning('x3')  #30   警告
    logging.error('x4')  #40   错误
    logging.critical('x5')  #50   立即解决的错误
    logging.log(10,'log')
    import traceback
    def func():
        try:
            a=a+1
    
        except Exception as e:
            # 获取当前错误的堆栈信息
            msg=traceback.format_exc()
            logging.error(msg)
    func()
    
    
  • 相关阅读:
    kali网卡配置文件
    haproxy配置文件详解和ACL功能
    Linux查询端口是否被占用的四种方法
    为Linux配置常用源:epel和IUS
    高可用之KeepAlived(2):keepalived+lvs
    高可用之KeepAlived(一):基本概念和配置文件分析
    应用负载均衡之LVS(四):详细剖析VS/NAT和VS/DR模式
    应用负载均衡之LVS(二):VS_TUN和VS_DR的arp问题
    wget命令的几个常用选项和示例
    应用负载均衡之LVS(一):基本概念和三种模式
  • 原文地址:https://www.cnblogs.com/shanghongyun/p/9566230.html
Copyright © 2011-2022 走看看