1.约束
1 class BaseMessage(object): 2 def send(self,x1): 3 """ 4 必须继承BaseMessage,然后其中必须编写send方法,用于完成具体业务逻辑 5 """ 6 raise NotImplementedError(".send()必须被重写") 7 8 class Email(BaseMessage): 9 def send(self,x1): 10 """ 11 必须继承BaseMessage,然后其中必须编写send方法 12 """ 13 pass 14 15 obj = Email() 16 obj.send(1)
抽象类和抽象方法的约束
1 from abc import ABCMeta,abstractmethod 2 3 class Base(metaclass=ABCMeta):#抽象类 4 def f1(self): 5 print(123) 6 7 @abstractmethod 8 def f2(self):#抽象方法 9 pass 10 11 class Foo(Base): 12 def f2(self): 13 print(666) 14 15 obj = Foo() 16 obj.f1()
接口的作用:接口是一种数据类型,主要用于约束派生类中必须实现指定的方法
抽象类的作用:约束继承它的派生类必须实现它其中的方法
抽象方法的作用:约束继承此抽象方法的类的派生类必须实现这个抽象方法
抽象类加抽象方法和接口的区别:
接口中不允许写代码,只能约束继承它的类中必须实现指定的方法
抽象类加抽象方法中可以写代码,约束继承抽象类的派生类中必须实现指定的抽象方法
2.异常处理
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路径的文件中,找到前缀为iprev的一行数据,获取数据并返回给调用者 12 1000,成功 13 1001,文件不存在 14 1002,关键字为空 15 1003,未知错误 16 """ 17 reponse = {'code':1000,'data':None} 18 19 try: 20 if not os.path.exists(path): 21 raise ExistsError() 22 if not prev: 23 raise KeyInvalidError() 24 25 except ExistsError as e: 26 response['code'] = 1001 27 response['data'] = "文件不存在" 28 except KeyInvalidError as e: 29 response['code'] = 1002 30 response['data'] = '关键字为空' 31 except Exception as e: 32 response['code'] = 1003 33 response['data'] = '未知错误' 34 return response
自定义异常:
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 obj: 10 print(obj.code,obj.msg) 11 12 13 class MyException(Exception): 14 def __init(self,code,msg): 15 self.code = code 16 self.msg = msg 17 18 try: 19 raise MyException(1000,'操作异常') 20 except KeyError as obj: 21 print(obj,111) 22 except MyException as obj: 23 print(obj,222) 24 except Exception as obj: 25 print(obj,333)
3.加密
1 import hashlib 2 3 def md5(s): 4 salt = 'efg' 5 s = s + salt #加盐 6 md = hashlib.md5() 7 md.update(s.encode("utf-8")) 8 return md.hexdigest() 9 print(md5("abcd"))
4.日志
配置logging基本的设置,然后在控制台输出日志
1 import logging 2 logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s') 3 logger = logging.getLogger(__name__) 4 5 logger.info("Start print log") 6 logger.debug("Do something") 7 logger.warning("Something maybe fail.") 8 logger.info("Finish")
运行时,在控制台输出:
2018-09-01 17:21:44,389 - __main__ - INFO - Start print log
2018-09-01 17:21:44,389 - __main__ - WARNING - Something maybe fail.
2018-09-01 17:21:44,389 - __main__ - INFO - Finish
logging中可以选择很多消息级别,如debug,info,warning,error以及critical.通过赋予logger或者handler不同的级别,开发者就可以只输出错误信息到特定的记录文件,或者在调试时只记录调试信息
参数的作用:
%(levelno)s:打印日志级别的数值
%(levelname)s:打印日志级别的名称
%(pathname)s:打印当前执行程序的路径,其实就是sys.argv[0]
%(filename)s:打印当前执行程序名
%(funcName)s:打印日志的当前函数
%(lineno)d:打印日志的当前行号
%(asctime)s:打印日志的时间
%(thread)d:打印线程ID
%(threadName)s:打印线程名称
%(process)d:打印进程ID
%(message)s:打印日志信息
将日志写入文件:
1 import logging 2 logger = logging.getLogger(__name__) 3 logger.setLevel(level = logging.INFO) 4 handler = logging.FileHandler("log.txt") 5 handler.setLevel(logging.INFO) 6 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 7 handler.setFormatter(formatter) 8 logger.addHandler(handler) 9 10 logger.info("Start print log") 11 logger.debug("Do something") 12 logger.warning("Something maybe fail.") 13 logger.info("Finish")
log.txt文件中的日志数据为:
2018-09-01 17:24:45,075 - __main__ - INFO - Start print log
2018-09-01 17:24:45,076 - __main__ - WARNING - Something maybe fail.
2018-09-01 17:24:45,076 - __main__ - INFO - Finish
如果要自定义日志的个数:
1 import logging 2 3 4 # 创建一个操作日志的对象logger(依赖FileHandler) 5 file_handler = logging.FileHandler('l1.log', 'a', encoding='utf-8') 6 file_handler.setFormatter(logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s")) 7 8 logger1 = logging.Logger('s1', level=logging.ERROR) 9 logger1.addHandler(file_handler) 10 11 12 logger1.error('123123123') 13 14 15 16 # 在创建一个操作日志的对象logger(依赖FileHandler) 17 file_handler2 = logging.FileHandler('l2.log', 'a', encoding='utf-8') 18 file_handler2.setFormatter(logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s")) 19 20 logger2 = logging.Logger('s2', level=logging.ERROR) 21 logger2.addHandler(file_handler2) 22 23 logger2.error('666')
这样就生成了两个日志,
l1.log中写入
2018-09-01 17:28:01,195 - s1 - ERROR -test0: 123123123
l2.log中写入:
2018-09-01 17:28:01,196 - s2 - ERROR -test0: 666