pyrhon类约束及异常处理和日志模块

类的约束

 class Base:     #对子类进行了约束,必须重写该方法
     def login(self):
         print('方法错误,必须用定义login方法')
         # 发现了notImplementedError继承他,直接重写他
         # raise NotImplementedError("你要重写一下login这个方法,否则报错!")    # 抛异常
 
 class Member(Base):
     def login(self):
         print('我的功能是普通用户登录')
 class Admin(Base):
     def login(self):
         print('我的功能是版主登录')
 class Houtai(Base):
     # def denglu(self):     #报错,上层程序员写代码没有按照规范来
     #     print('我的功能是管理员登录')
 
     def login(self):
         print('我的功能是管理员登录')
 
 def Deng(obj):      # 整合这些个功能
     obj.login()
 m = Member()
 admin = Admin()
 ht = Houtai()
 Deng(m)
 Deng(admin)
 Deng(ht)
 结果
 我的功能是普通用户登录
 我的功能是版主登录
 我的功能是管理员登录

抽象类和抽象方法
抽象方法不需要给出具体的方法体,抽象方法内只写一个pass就可以了
在一个类中如果有一个方法是抽象方法,那么这个类一定是一个抽象类
抽象类中,如果有抽象方法,此时这个类不能创建对象
如果一个类中所有的方法都是抽象方法,这个类可以被称为接口类
写一个抽象方法:
导入一个模块

 1 from abc import ABCMeta,abstractmethod
 2 class Animal(metaclass=ABCMeta):    #就是个抽象类
 3     @abstractmethod
 4     def chi(self):  # 吃只是一个抽象概念,没办法完美的描述出来吃什么东西
 5         pass
 6 
 7     def he(self):   # 抽象类中可以有正常的方法
 8         print('喝水')
 9 
10 class Cat(Animal):  # 此时Cat里面也有一个抽象方法,此时的Cat是创建不了对象的
11     pass
12 
13 class Dog(Animal):
14     def chi(self):  # 重写父类中的抽象方法
15         print('狗吃肉')
16 # c = Cat()
17 # c.chi()   #TypeError: Can't instantiate abstract class Cat with abstract methods chi
18 d = Dog()
19 d.chi()
20 结果
21 狗吃肉
复制代码

MD5加密

复制代码
 1 import hashlib
 2 obj = hashlib.md5(b'盐') #盐又称杂质,通常密码中添加,虽然MD5不可逆推,但是不加盐可以撞库算出密码
 3 obj.update('密码'.encode('utf-8'))
 4 print(obj.hexdigest())
 5 结果
 6 一串MD5数字
 7 
 8 
 9 案例
10 import hashlib
11 #定义自己的MD5功能
12 def my_md5(s):
13     obj = hashlib.md5(b'zazhi')      # 加盐
14     obj.update(s.encode('utf-8'))    #把要加密的内容给md5
15     return obj.hexdigest()
16 print(my_md5('123456'))
17 
18 user = 'bob'
19 pwd = 'abf6a5b33687f111e79f615a6d1fb76a'
20 
21 #登录
22 uname = input('用户名:')
23 upwd = input('密码:')
24 if uname == user and my_md5(upwd) == pwd:
25     print('登录成功')
26 else:
27     print('登录失败')
复制代码

异常处理

复制代码
 1 print(1 / 0)
 2 print('哈哈哈哈哈')
 3 结果
 4 ZeroDivisionError: division by zero
 5 
 6 # 0不能做除数,在程序执行的时候产生了一个错误
 7 # 系统会抛出这个错误,如果没有人处理,错误就会显示给用户
 8 
 9 单行异常处理
10 try:
11     print(1/0)
12 except ZeroDivisionError:
13     print('报错ZeroDivisionError')
14 结果
15 报错ZeroDivisionError
复制代码

多行异常处理
如果在异常处理的时候,其中一个报错类型触发,其他的报错类型就不会触发,处理完触发的报错后自动退出

复制代码
 1 try:
 2     print(1/10)
 3     f =  open('','r')
 4     dic = {[]:123}
 5 except ZeroDivisionError:        #处理ZeroDivisionError类型错误
 6     print('报错ZeroDivisionError')
 7 except FileNotFoundError:       #处理FileNotFoundError类型错误
 8     print('报错FileNotFoundError')
 9 except Exception:               # 可以处理所有错误
10     print('其他所有类型错误')
11 else:                           # 当try中的代码不产生任何错误的时候,会自动的执行else里的代码
12     print('没有错误时候执行这句话')
13 finally:                        # 最终,不管出错还是不出错,都要执行最后的finally,一般用来收尾
14     print('无论有没有错误都执行')
15 结果
16 0.1
17 报错FileNotFoundError
18 无论有没有错误都执行
复制代码

自定义异常
class 类(Exception):
    pass
随便写一个类,这个类只要继承了Exception这个类就是一个异常类就可以作为raise对象
抛出异常
raise 异常类(错误信息)

复制代码
 1 class TextException(Exception):     #自定义异常
 2     pass
 3 
 4 def Text(a,b):
 5     if (type(a) == int or type(a) == float ) and (type(b) == int or type(b) == float):
 6         return a + b
 7     else:
 8         raise TextException('Text函数错误')     #raise 抛出异常
 9 print(Text('哈哈',2))
10 结果
11 Traceback (most recent call last):
12   File "E:/Py3Practise/day01/test.py", line 11, in <module>
13     print(Text('哈哈',2))
14   File "E:/Py3Practise/day01/test.py", line 10, in Text
15     raise TextException('Text函数错误')
16 __main__.TextException: Text函数错误
复制代码

堆栈
import traceback
traceback.format_exc()

复制代码
 1 import traceback        # 用来查看堆栈信息(错误信息叫堆栈信息)
 2 class GenderException(Exception):
 3     pass
 4 class Person:
 5     def __init__(self,name,gender):
 6         self.name = name
 7         self.gender = gender
 8     def xz(self):
 9         print(f'{self.name}在洗澡')
10 def nan(ren):
11     if ren.gender == '男':
12         ren.xz()
13     else:
14         raise GenderException('男女有别')   # 抛异常是很重要的
15 try:
16     p1 = Person('bob','不详')
17     p2 = Person('jack','男')
18     nan(p1)
19     nan(p2)
20 except GenderException:
21     ret = traceback.format_exc()    # 查看堆栈信息,看错误的
22     print(ret)
23     # print('报错了')               #自定义堆栈信息
24 结果
25 Traceback (most recent call last):
26   File "E:/Py3Practise/day01/test.py", line 20, in <module>
27     nan(p1)
28   File "E:/Py3Practise/day01/test.py", line 16, in nan
29     raise GenderException('男女有别')
30 GenderException: 男女有别
复制代码

日志处理
import logging
日志等级:
critical: 50
error: 40
warning: 30
info: 20
debug: 10

复制代码
 1 记录日志初级版本
 2 配置好日志的处理,默认就是GBK
 3 logging.basicConfig(filename='x1.txt', # 把日志信息写入的文件名
 4                     format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
 5                     datefmt='%Y-%m-%d %H:%M:%S', # 时间的格式
 6                     level=30)   # 当前配置表示 30及以上的日志信息会被写入日志文件,30以下的不记录
 7 
 8 # 向日志文件写入内容
 9 logging.critical("系统要爆炸")   # 50 几乎是最高的
10 logging.error("服务程序宕机")    # 40 平时使用最多的就是他
11 logging.warn("服务发生了一个警告") # 30 警告
12 logging.warning("和warn一样发生了一个警告")
13 logging.info("提示信息")        # 20 提示信息
14 logging.debug("调试信息开发要开着") # 10 详细执行信息
15 logging.log(999, "自定义了一个日志级别")
16 日志格式
17 2018-12-21 19:52:53 - root - CRITICAL -test: 系统要爆炸
18 2018-12-21 19:52:53 - root - ERROR -test: 服务程序宕机
19 2018-12-21 19:52:53 - root - WARNING -test: 服务发生了一个警告
20 2018-12-21 19:52:53 - root - WARNING -test: 和warn一样发生了一个警告
21 2018-12-21 19:52:53 - root - INFO -test: 提示信息
22 2018-12-21 19:52:53 - root - DEBUG -test: 调试信息开发要开着
23 2018-12-21 19:52:53 - root - Level 999 -test: 自定义了一个日志级别
复制代码

创建一个操作日志的对象logger(依赖FileHandler)

复制代码
 1 import logging
 2 file_handler = logging.FileHandler('test.log', 'a', encoding='utf-8') # 创建文件
 3 file_handler.setFormatter(logging.Formatter(
 4     fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s")) # 设置日志文件的格式
 5 logger1 = logging.Logger('测试程序CRM系统', level=10) # 创建一个日志文件处理对象
 6 logger1.addHandler(file_handler)                    # 把文件添加到日志
 7 logger1.error("这是测试程序CRM系统调试debug日志")
 8 日志格式
 9 2018-12-21 20:03:09,148 - 测试程序CRM系统 - ERROR -test: 这是测试程序CRM系统调试debug日志
10 
11 
12 file_handler2 = logging.FileHandler('l2.log', 'a', encoding='utf-8')
13 file_handler2.setFormatter(logging.Formatter(
14     fmt="%(asctime)s - %(name)s -%(levelname)s -%(module)s: %(message)s"))
15 logger2 = logging.Logger('自动化系统', level=logging.DEBUG)
16 logger2.addHandler(file_handler2)
17 logger2.error("这个自动化系统调试DEBUG日志")
18 日志格式
19 2018-12-21 20:03:09,148 - 自动化系统 -ERROR -test: 这个自动化系统调试DEBUG日志
20 
21 
22 事例
23 import logging
24 file_handler = logging.FileHandler('test.log', 'a', encoding='utf-8') # 创建文件
25 file_handler.setFormatter(logging.Formatter(
26     fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s")) # 设置日志文件的格式
27 logger1 = logging.Logger('测试程序CRM系统', level=10) # 创建一个日志文件处理对象
28 logger1.addHandler(file_handler) # 把文件添加到日志
29 logger1.error("这是测试程序CRM系统调试debug日志")
30 
31 file_handler2 = logging.FileHandler('l2.log', 'a', encoding='utf-8')
32 file_handler2.setFormatter(logging.Formatter(
33     fmt="%(asctime)s - %(name)s -%(levelname)s -%(module)s: %(message)s"))
34 logger2 = logging.Logger('自动化系统', level=logging.DEBUG)
35 logger2.addHandler(file_handler2)
36 logger2.error("这个自动化系统调试DEBUG日志")
37 
38 import traceback
39 class GenderException(Exception):
40     pass
41 
42 class Person:
43     def __init__(self,name,gender):
44         self.name = name
45         self.gender = gender
46         logger1.info(f'姓名{self.name},性别{self.gender}')
47     def xz(self):
48         print(f'{self.name}在洗澡')
49 
50 class Zt:
51     def nan(self,ren):
52         if ren.gender == '男':
53             ren.xz()
54         else:
55             raise GenderException("我这里要的是男人")
56 
57     def nv(self,ren):
58         if ren.gender == '女':
59             ren.xz()
60         else:
61             raise GenderException("我这里要的是女人")
62 try:
63     p1 = Person('jack','男')
64     p2 = Person('bob','女')
65     zaotang = Zt()
66     zaotang.nan(p2)
67     zaotang.nv(p1)
68 except GenderException:
69     print('走错了')
70     logger1.error('走错屋了')
71     logger1.error(traceback.format_exc())
72 结果
73 走错了
74 日志结果
75 2018-12-21 20:25:48,478 - 测试程序CRM系统 - ERROR -test: 这是测试程序CRM系统调试debug日志
76 2018-12-21 20:25:48,478 - 测试程序CRM系统 - INFO -test: 姓名jack,性别男
77 2018-12-21 20:25:48,478 - 测试程序CRM系统 - INFO -test: 姓名bob,性别女
78 2018-12-21 20:25:48,479 - 测试程序CRM系统 - ERROR -test: 走错屋了
79 2018-12-21 20:25:48,479 - 测试程序CRM系统 - ERROR -test: Traceback (most recent call last):
80   File "E:/Py3Practise/day01/test.py", line 46, in <module>
81     zaotang.nan(p2)
82   File "E:/Py3Practise/day01/test.py", line 35, in nan
83     raise GenderException("我这里要的是男人")
84 GenderException: 我这里要的是男人
原文地址:https://www.cnblogs.com/selina1997/p/10167346.html