# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2019/6/18 22:33
from
__future__
import
unicode_literals
import
time
"""
建議8:利用assert來發現問題
"""
# assert語法
a
=
1
# 斷言`a != 1`, 拋出異常`sss`
# assert a != 1, 'sss'
# 不要濫用斷言
# 如果python本身的異常能夠處理,就不要用斷言
# 不要使用斷言來檢查用戶輸入
# 當對函數返回值的合理性進行檢查時,可進行斷言
# 當條件是業務邏輯繼續進行的先決條件時,可進行斷言
"""
建議9:數據交換的時候,不推薦使用中間變量
"""
c
=
1
b
=
2
print
(
'c:'
,
c
,
'b:'
,
b
)
c
,
b
=
b
,
c
print
(
'c:'
,
c
,
'b:'
,
b
)
"""
建議10、充分利用Lazy evaluation的特性
"""
# 1、避免不必要的計算,帶來性能上的提升
# 在一個表達式中有or、and時,將or放到前面
# 2、節省空間,使得無限循環的數據結構成為可能
"""
建議11、理解枚舉替代實現的缺陷
"""
# 枚舉的實現方式有
# 1、使用類屬性
class
Seasons
(
object
)
:
Spring
=
0
Summer
=
1
Autumn
=
3
Winter
=
4
# 簡化上面的例子
class
Seasons
(
object
)
:
Spring
,
Summer
,
Autumn
,
Winter
=
range
(
4
)
print
(
Seasons
.
Spring
)
# 2、借助函數
def
enum
(
*
args
)
:
return
type
(
'Enum'
,
(
object
,
)
,
dict
(
zip
(
args
,
range
(
len
(
args
)
)
)
)
)
Seasons
=
enum
(
'Spring'
,
'Summer'
,
'Autumn'
,
'Winter'
)
print
(
Seasons
.
Spring
)
# 3、使用collections.namedtuple
import
collections
Seasons
=
collections
.
namedtuple
(
'Seasons'
,
'Spring Summer Autumn Winter'
)
.
_make
(
range
(
4
)
)
print
(
Seasons
.
Summer
)
"""
建議12、不推薦使用type來進行類型檢查
"""
# 使用isinstance來判斷類型
u
=
1
if
isinstance
(
u
,
int
)
:
print
(
'{u} type is int.'
.
format
(
u
=
u
)
)
"""
建議13、盡量轉換為浮點類型后再在做除法
"""
# 編譯器會進行強制類型轉換
"""
建議14、警惕eval()的安全漏洞
"""
b
=
None
# 輸出結果為`s`
print
(
eval
(
'"s" if b is None else "xxx"'
)
)
"""
建議15、使用enumerate獲取迭代器的索引和值
"""
li
=
[
i
for
i
in
'abcde'
]
for
index
,
element
in
enumerate
(
li
)
:
print
(
'index:{index},element:{element}'
.
format
(
index
=
index
,
element
=
element
)
)
# 使用下面的語句會更好簡單
[
print
(
'index:{index},element:{element}'
.
format
(
index
=
s
[
0
]
,
element
=
s
[
1
]
)
)
for
s
in
enumerate
(
li
)
]
"""
建議16、分清`==`與`is`的適用場景
"""
# 1、is是比較的內存地址
# 2、==是比較兩個對象的值、內部調用了__eq__()
"""
建議17、考慮兼容性、盡可能使用unicode
"""
# 1、python的內建字符串有兩種:str和unicode、它們的基類都是basestring
# 2、unicode字符串為不同語言設置了唯一的二進制表示形式
# 3、對于編碼格式不一致的數據,先解碼為unicode、后進行編碼
file_name
=
open
(
'test.txt'
,
'r'
,
encoding
=
'utf-8'
)
print
(
file_name
.
read
(
)
.
encode
(
'utf-8'
)
.
decode
(
'utf-8'
)
)
file_name
.
close
(
)
# 編碼參數 錯誤處理
# str.encode(encoding='utf-8', errors='strict')
# str.decode(encoding='utf-8', errors='strict')
# errors的值有:
# `strict`默認為嚴格的處理方式,編碼錯誤時,會拋出異常
# `ignore`,忽略不可轉換的字符
# `replace`,將不可轉換的字符,用?的值代替
import
sys
# 獲取Python中默認編碼方式
print
(
sys
.
getdefaultencoding
(
)
)
# 編碼申明
# !/usr/bin/python3
# -*- coding: utf-8 -*-
"""
建議18、構建合理的包層次來管理model
"""
# 1、直接導入包 import package
# 2、使用from package import model
# 3、使用__all__ = []來限定導入
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
