1. 类的约束
1. 写一个父类. 父类中的某个方法要抛出一个异常 NotImplementedError
class Base: def login(self): raise NotImplementedError("没有实现登录") class Person(Base): def login(self): print("正常使用") class SpecialPerson(Base): def denglu(self): print("非正常") def func(obj): obj.login() p1 = Person() p2 = SpecialPerson() func(p1) func(p2)
2. 抽象类和抽象方法
from abc import ABCMeta, abstractmethod
class Base(metaclass = ABCMeta):
@abstractmethod
def fangfa(self):
pass
from abc import ABCMeta,abstractmethod class Animal(metaclass = ABCMeta): @abstractmethod def chi(self):pass def run(self): print("能跑") class Cat(Animal): def chi(self): print("吃鱼") def dong(self): print("guyong") c = Cat() c.chi() c.dong() c.run()
2. 异常处理.
try except raise finally
try:
代码
except 异常类:
除了错, 如何处理异常
except 异常类:
除了错, 如何处理异常
except 异常类:
除了错, 如何处理异常
else:
当程序不出错
finally:
不管出不出错, 都要执行
raise 异常类("信息")
如何自己定义异常
class 类(Exception):
pass
堆栈
import traceback
traceback.format_exc()
import traceback class GenderException(Exception): pass class Person: def __init__(self,name,gender): self.name = name self.gender = gender def xizao(self): print(f"{self.name}在洗澡") def zaotang(ren): if ren.gender == "男": ren.xizao() else: raise GenderException("性别不对,去对门看看") try: p1 = Person("tom","男") p2 = Person("jerry","mouse") zaotang(p1) zaotang(p2) except GenderException: ret = traceback.format_exc() print(ret)
3. MD5加密
import hashlib
obj = hashlib.md5(b'盐')
obj.update(b"要加密的内容")
print(obj.hexdigest())
import hashlib def my_md5(c): obj = hashlib.md5(b"safgd") obj.update(c.encode("utf-8")) return obj.hexdigest() print(my_md5("1996"))
4. 日志处理
等级:
critical: 50
error:40
warning:30
info:20
debug:10
import logging logging.basicConfig(filename='x1.txt', # 把日志信息写入的文件名 format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S', # 时间的格式 level=20) # 当前配置表示 10以上的分数会被写入日件 logging.critical("高") logging.error("很高") logging.warning("一般") logging.info("较低") logging.debug("最低") logging.log(500,"自己定") file_handler = logging.FileHandler('l1.log', 'a', encoding='utf-8') # 创建文件 file_handler.setFormatter(logging.Formatter( fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s")) # 设置日志文件的格式 logger1 = logging.Logger('腾讯qq', level=40) # 创建一个日志文件处理对象 logger1.addHandler(file_handler) # 把文件添加到日志 logger1.error("运行出错了") file_handler2 = logging.FileHandler('l2.log', 'a', encoding='utf-8') file_handler2.setFormatter(logging.Formatter( fmt="%(asctime)s - %(name)s -%(levelname)s -%(module)s: %(message)s")) logger2 = logging.Logger('百度贴吧', level=logging.DEBUG) logger2.addHandler(file_handler2) logger2.debug("有点小问题")