日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

python编程小提示

發(fā)布時(shí)間:2023/11/27 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python编程小提示 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

一.面向?qū)ο蟮募s束

1.基于人為的約束

?

calss BaseMessage(object):def send(self,x):#必須繼承BaseMessage,然后其中必須編寫send方法.用于具體業(yè)務(wù)邏輯.raise NotImplementedError(".send() 必須被重寫")
class Email(BaseMessage):def  send(self,x):#必須繼承BaseMessage,然后其中必須編寫send方法,用于完成具體邏輯return x
obj = Email()
obj,send(1)

?

如果Email類中未編寫send(),仍繼續(xù)使用繼承父類的send(),則會(huì)報(bào)錯(cuò)打印? '.send() 必須重寫'.父類中raise NotImplementedError有約束作用,提示子類必須編寫send()方法.

2.抽象類和抽象方法的約束

from abc import ABCMeta,abstractmethodclass Base(metaclass=ABCMeta):  # 定義抽象類def f1(self):print('酸辣')@abstractmethoddef f2(self):     #抽象方法pass
class Foo(Base):def f2(self):print('')obj = Foo()
obj.f1()

Foo類只有編寫父類抽象方法f2()時(shí)候,程序才可以正常進(jìn)行,否則報(bào)錯(cuò).

二.自定義異常處理

?有時(shí)在編寫代碼的時(shí)候我們需要編寫異常情況,用到Exception萬能處理時(shí),有一個(gè)小小的缺點(diǎn),就是不能提醒我們此時(shí)程序報(bào)的是什么錯(cuò)誤,所以有時(shí)候我們要針對(duì)一些情況自定義異常處理.

import os
class ExistsError(Exception):pass
class KeyInvalidError(Exception):pass
def new_func(path,prev):response = {'code':1000,'data':None}try:if not os.path.exists():raise ExistsError()if not prev:raise KeyInvalidError()passexcept ExistsError as e:response['code'] = 1001response['data'] = '文件不存在'except KeyInvalidError as e:response['code'] = 1002response['data'] = '關(guān)鍵字為空'except Exception as e:response['code'] =1003response['data'] = '未知錯(cuò)誤'return response
print(new_func("C:\劉清揚(yáng)\PyCharm 2018.1.4\python.py","we"))

這樣我們就可以得到當(dāng)'文件不存在','關(guān)鍵字為空'時(shí)出現(xiàn)的報(bào)錯(cuò)了.

class MyException(Exception):def __init__(self,code,msg):self.code = codeself.msg = msg
try:raise MyException(100,'操作異常')except KeyError as obj:print(obj,1111)
except MyException as obj:print(obj,222)                  #打印(100,'操作異常') 222
except Exception as obj:print(obj,3333)

三.為你的文件加密

在登錄程序時(shí),為了不讓你的密碼不被盜取,所以應(yīng)該在儲(chǔ)存密碼時(shí)將明文改為密人,讓隱私更安全.

import hashlibdef md5(pwd):obj = hashlib.md5()      obj.update(pwd.encode('utf-8'))return obj.hexdigest()
print(md5('21312e'))    #打印d09c5c2fd74e97e2e9e98bbc8d0a3e4b

將密碼21312e轉(zhuǎn)為密文??09c5c2fd74e97e2e9e98bbc8d0a3e4b

還可以繼續(xù)為我們的密碼加鹽(嚴(yán))

import hashlib
Salt = b'qwqw1212'    #加嚴(yán)
def md5(pwd):obj = hashlib.md5(Salt)obj.update(pwd.encode('utf-8'))return obj.hexdigest()
print(md5('21312e'))   打印81dda1ec99f8327b68659dbc56ee46c5

四.自定義日志

當(dāng)我們寫好程序給用戶體驗(yàn)時(shí),如果用戶操作出報(bào)錯(cuò)信息,我們直接排查bug時(shí)將非常不方便.這時(shí)候我們編寫一個(gè)日志功能,將報(bào)錯(cuò)詳細(xì)錄入,將會(huì)方便我們以后工作.

import logging
logger1 = logging.basicConfig(filename='x1.txt',format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',datefmt='%Y-%m-%d %H:%M:%S',level=30)  #當(dāng)level大于等于30時(shí),會(huì)被錄入日志
logging.error('x4')
logging.error('x5')

當(dāng)我們想要將兩個(gè)(或多個(gè))報(bào)錯(cuò)信息分別錄入兩個(gè)(多個(gè))時(shí),需要自定義日志.

import logging
# 創(chuàng)建一個(gè)操作日志的對(duì)象logger(依賴FileHandler)
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('s1', level=logging.ERROR)
logger1.addHandler(file_handler)
logger1.error('123123123')# 在創(chuàng)建一個(gè)操作日志的對(duì)象logger(依賴FileHandler)
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('s2', level=logging.ERROR)
logger2.addHandler(file_handler2)logger2.error('666')

?五.python2和python3的區(qū)別

字符串:? ?python2:unicode? ?v = u"root"? ?本質(zhì)上是用unicode存儲(chǔ)(萬國(guó)碼)

     (str/bytes)? ? ? ? ? v = "root"? ? ? 本質(zhì)上用字節(jié)存儲(chǔ)

    python3:str? ? v = "root"? ? 本質(zhì)上是用unicode存儲(chǔ)(萬國(guó)碼)

        bytes? ?v = b"root"? ?本質(zhì)上用字節(jié)存儲(chǔ)

編碼:? ?python2: 默認(rèn)ascii? 文件頭可以修改,? #-*- encoding:utf-8

    python3: 默認(rèn)utf-8? 文件頭也可以修改

繼承:? python2:? 經(jīng)典類/新式類(object)

? ? ? ? ? ?python3:新式類

輸入:? python2:? ? v = raw_input('')

? ? ? ? ? python3? ? ? v = input('')

打印:? ?python2 :? print 'xx'

? ? ?  python3: print('xx')

轉(zhuǎn)載于:https://www.cnblogs.com/liuqingyang/p/9395564.html

總結(jié)

以上是生活随笔為你收集整理的python编程小提示的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。