約束某各種
用於約束其派生類,保證其派生類中有send方法,否則執行可能會報錯
約束其派生類,python中用類來實現,Java和C#中用接口或類來實現
(1) 對於Java/C#:
類:(java和C#是先編譯後運行的,因此若是不知足條件,一開始就會報錯,根本沒法運行)
1 class Foo: 2 def f1(self): 3 pass #可認爲拋出異常
4
5 抽象類:約束他的派生類必須實現他其中的抽象方法 6 abstact class Foo: 7 def f1(self): #此方法能夠不用繼承
8 pass
9
10 abstact def f2(self): 11 pass
12 class Bar: 13 def f2(self): 14 pass
1 abstact class Foo: 2 def f1(self): #此方法能夠不用繼承
3 pass
4
5 abstact def f2(self): 6 pass
7 class Bar: 8 def f2(self): 9 pass
1 interface Foo: 2 def f1(self,x1):pass
3
4 def f2(self,x1):pass
5
6 interface Bar: 7 def f3(self,x1):pass
8
9 def f4(self,x1):pass
10
11 class Aou(Foo,Bar): 12 def f1(self,x1):pass
13
14 def f2(self,x1):pass
15
16 def f3(self,x1):pass
17
18 def f4(self,x1):pass
(2)python中:java
1 class BaseMessage: 2 def send(self): 3 '''
4 必須繼承BaseMessage,而後其中必須編寫send方法,用於完成具體的業務邏輯 5 '''
6 # raise Exception('...')
7 raise NotImplementedError('send方法必須被重寫') #更專業 #NotImplementedError是沒有實現的意思
8
9 class Email(BaseMessage): 10 def send(self): 11 pass #發送郵件
12
13 def f1(self): 14 pass
15
16 def f2(self): 17 pass
18
19 class Wechat(BaseMessage): 20 def send(self): 21 pass
22
23 def f3(self): 24 pass
25
26 class Messege(BaseMessage): 27 def send(self): 28 pass
29
30 def f4(self): 31 pass
32
33 def func(arg): 34 '''
35 報警通知 36 :param arg: 37 :return: 38 '''
39 arg.send()
1 from abc import ABCMeta,abstractmethod 2 class Base(metaclass=ABCMeta): #定義了一個抽象類
3 def f1(self): 4 print(123) 5
6 @abstractmethod 7 def f2(self): #定義了一個抽象方法
8 pass
9
10 class Foo(Base): 11 def f2(self): 12 print(666) 13
14 obj=Foo() 15 obj.f1() 16 obj.f2()
總結:
1.什麼是接口,以及做用?
接口是一種數據類型,用於約束派生類中必須實現指定方法
python中不存在,在Java和C#中存在
2.python中用什麼來約束
抽象方法,抽象類(編寫上麻煩)
認爲主動拋出異常
3.約束時拋出的異常是否能夠用其餘的
不專業:raise Exception('...')
專業:raise NotImplementedError('send方法必須被重寫')
4.之後看代碼時,揣摩寫代碼的人的心思
5.應用場景:
多個類,內部都必須有某各種或某個方法時,須要使用基類+異常進行約束
1 class Base: 2 def login(self): 3 raise NotImplementedError('...') 4
5 class Student(Base): 6 def login(self): 7 pass
8 def score(self): 9 pass
10
11 class Teather(Base): 12 def login(self): 13 pass
14
15 def exam(self): 16 pass
17
18 class Messaer(Base): 19 def login(self): 20 pass
21 def set(self): 22 pass
1 import os 2 def func(path,prev): 3 '''
4 去路徑的文件中,找到前綴爲prev的一行數據,獲取數據並返回給調用者' 5 1000 成功 6 1001 文件不存在 7 1002 關鍵字爲空 8 1003 未知錯誤 9 :param path: 10 :param prev: 11 :return: 12 '''
13 response ={'code':1000,'data':None} 14 try: 15 if not os.path.exists(path): 16 response['code'] = 1001
17 response['data'] = '文件不存在'
18 return response 19 if not prev: 20 response['code'] = 1002
21 response['data'] = '關鍵字爲空'
22 return response 23 except Exception as e: 24 response['code']=1003
25 response['data']='未知錯誤'
26 return response 27 def func2(): 28 return 8
29 def show(): 30 v1=func() 31 v2=func2()
1 class ExistsError(Exception): #自定義異常類,自定義的異常類要繼承Exception
2 pass
3 class KeyInvalidError(Exception): 4 pass
5 import os 6 def new_func(path,prev): 7 '''
8 去路徑的文件中,找到前綴爲prev的一行數據,獲取數據並返回給調用者' 9 1000 成功 10 1001 文件不存在 11 1002 關鍵字爲空 12 1003 未知錯誤 13 '''
14 response ={'code':1000,'data':None} 15 try: #目的就是爲了讓try中的代碼簡單明瞭
16 if not os.path.exists(path): 17 raise ExistsError 18 if not prev: 19 raise KeyInvalidError 20 except ExistsError as e: 21 response['code'] = 1001
22 response['data'] = '文件不存在'
23 except KeyInvalidError as e: 24 response['code'] = 1002
25 response['data'] = '關鍵字爲空'
26 except Exception as e: 27 response['code']=1003
28 response['data']='未知錯誤'
29 return response 30 def func2(): 31 return 8
32 def show(): 33 v1=new_func() 34 v2=func2()
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 e: #捕獲異常
10 print(e.code,e.msg)
import hashlib #幫助加密的模塊
obj=hashlib.md5(b'6khiy78g76tfmjyvf64') # 寫入要加加密的字節
obj.update('admin'.encode('utf-8')) v=obj.hexdigest() #獲取密文
print(v)
關鍵詞:撞庫 將常見的密文概括總結,一個一個試
加鹽:obj=hashlib.md5(b'6khiy78g76tfmjyvf64')
1 Hash objects have these methods: 2 - update(arg): Update the hash object with the bytes in arg. Repeated calls 3 are equivalent to a single call with the concatenation of all 4 the arguments. 5 - digest(): Return the digest of the bytes passed to the update() method 6 so far. 7 - hexdigest(): Like digest() except the digest is returned as a unicode 8 object of double length, containing only hexadecimal digits. 9 - copy(): Return a copy (clone) of the hash object. This can be used to 10 efficiently compute the digests of strings that share a common 11 initial substring.
1 import hashlib 2 mi=b'6khiy78g76tfmjyvf64'
3 def md5(ped): 4
5 obj=hashlib.md5(mi) 6
7 obj.update('admin'.encode('utf-8')) 8
9 return obj.hexdigest() 10
11 name=input('親輸入用戶名') 12 pwd=input('親輸入用密碼') 13
14 if name=='ninini' and md5(pwd)=='263930cf6ae488d074e32def60d973cc': 15 print('登陸成功')
爲何要有日誌:
給開發人員看,用於排查錯誤
import logging #路徑或文件名
logger=logging.basicConfig(filename='log.log', format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S %p', level=10) #用於控制日誌的錯誤級別
logging.debug('x1') #10 正常測試
logging.info('x2') #20 正常的信息
logging.warning('x3') #30 警告
logging.error('x4') #40 錯誤
logging.critical('x5') #50 當即解決的錯誤
logging.log(10,'log') def func(): try: a=a+1
except Exception as e: print(e) logging.error(str(e)) func()
日誌錯誤處理:
import logging #路徑或文件名
logger=logging.basicConfig(filename='log.log', format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S %p', level=10) #用於控制日誌的錯誤級別
logging.debug('x1') #10 正常測試
logging.info('x2') #20 正常的信息
logging.warning('x3') #30 警告
logging.error('x4') #40 錯誤
logging.critical('x5') #50 當即解決的錯誤
logging.log(10,'log') import traceback def func(): try: a=a+1
except Exception as e: # 獲取當前錯誤的堆棧信息
msg=traceback.format_exc() logging.error(msg) func()