1. 類的約束 1. 寫一個父類. 父類中的某個方法要拋出一個異常 NotImplementedError 2. 抽象類和抽象方法 from abc import ABCMeta, abstractmethod class Base(metaclass = ABCMeta): @abstractme ...
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("有點小問題")