1,约束 class BaseMessage(object): def send(self,x1): raise NotImplementedError(".send() 必须被从新写入.") class Email(BaseMessage): def send(self,x1): #必须继承BaseMessage,然后其中必须编写send方法.用于完成具体业务逻辑 pass obj = Email() obj.send() #2抽象类和抽象方法. from abc import ABCMeta, abstractclassmethod class Base(metaclass=ABCMeta):#这是一个抽象类 def __init__(self, name, age): self.name = name self.age = age print() def func(self): print("In prosperity our friends know us; in adversity we know our friends.") @abstractclassmethod#抽象方法 def func2(cls): pass class Fpp(Base): def func2(cls): print(666) obj = Fpp(1,2) obj.func() 3.如何自定义异常 class MyException(Exception): def __init__(self, code, msg): self.code = code self.msg = msg try: raise MyException(100, "基本操作之-操作异常") except KeyError as obj: print(obj, 1111) except MyException as obj: print(obj, 2222) except Exception as obj: print(obj, 3333) #(100, '基本操作之-操作异常') 2222 3.加密 import hashlib Salt = b"12313213asdf" def md5(pwd): #实例化对象 obj = hashlib.md5(Salt) #写入要加密的字节 必须进行编码获得字节,文字不行 obj.update(pwd.encode("utf-8")) #获取密文7883ad16b4e4565434d6fce3f62c951e return obj.hexdigest() print(md5("find")) user = input("请输入用户名:") pwd = input("请输入密码:") if user == "oldboys" and md5(pwd) == "7883ad16b4e4565434d6fce3f62c951e": print("login success") else: print("fail") #请输入用户名:oldboys #请输入密码:find # success 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()