網(wǎng)站首頁 編程語言 正文
1. 避免多層分支嵌套
Python
中利用縮進(jìn)來替代 { }。如果多個 if 嵌套, 堪稱 ” 嵌套 if 地獄 “
下面的代碼直接翻譯了原始條件分支,導(dǎo)致代碼可讀性和維護(hù)性很差。
def buy_fruit(nerd, store): ? ? """去水果店買蘋果 ? ?? ? ? - 先得看看店是不是在營業(yè) ? ? - 如果有蘋果的話,就買 1 個 ? ? - 如果錢不夠,就回家取錢再來 ? ? """ ? ? if store.is_open(): ? ? ? ? if store.has_stocks("apple"): ? ? ? ? ? ? if nerd.can_afford(store.price("apple", amount=1)): ? ? ? ? ? ? ? ? nerd.buy(store, "apple", amount=1) ? ? ? ? ? ? ? ? return ? ? ? ? ? ? else: ? ? ? ? ? ? ? ? nerd.go_home_and_get_money() ? ? ? ? ? ? ? ? return buy_fruit(nerd, store) ? ? ? ? else: ? ? ? ? ? ? raise MadAtNoFruit("no apple in store!") ? ? else: ? ? ? ? raise MadAtNoFruit("store is closed!")
我們利用取反的方式,“提前結(jié)束” 來優(yōu)化這段代碼:
def buy_fruit(nerd, store): ? ? if not store.is_open(): ? ? ? ? raise MadAtNoFruit("store is closed!") ? ? if not store.has_stocks("apple"): ? ? ? ? raise MadAtNoFruit("no apple in store!") ? ? if nerd.can_afford(store.price("apple", amount=1)): ? ? ? ? nerd.buy(store, "apple", amount=1) ? ? ? ? return ? ? else: ? ? ? ? nerd.go_home_and_get_money() ? ? ? ? return buy_fruit(nerd, store)
“提前結(jié)束” :指在函數(shù)內(nèi)使用 return 或 raise 等語句提前在分支內(nèi)結(jié)束函數(shù)。
利用逆向思維,當(dāng)分支條件不滿足時,我們直接結(jié)束這段代碼,這樣更容易閱讀。
2. 封裝過于復(fù)雜的邏輯判斷
如果條件分支中有過多的判斷條件 and | not | or, 可以將這樣的部分封裝起來。
if person.is_student and person.age > 20 and person.is_male: ?? ?pass
這樣封裝的部分更有可解釋性,更容易被人理解。
最重要的事還解決了,相同代碼多次出現(xiàn)的問題。
if person.identity() and person.gender(): ?? ?pass
3. 不同分支下的重復(fù)代碼
下面的代碼很難讓人直觀分別出不同:
if person.is_student(): ?? ?record_imformation( ?? ?name = person.name, ?? ?age = person.name, ?? ?address = person.address, ?? ?student_number = 10011, ?? ?recorded = now(), ?? ?) else: ?? ?update_information( ?? ?name = person.name, ?? ?age = person.name, ?? ?address = person.address, ?? ?updated = now(), ?? ?)
關(guān)注這些由分支產(chǎn)生的重復(fù)代碼塊,通過轉(zhuǎn)化簡化它們。
if person.is_student(): ?? ?imformation_func = ?record_imformation ?? ?extra_args = {'student_number' : 10011, 'recorded' : now() } else: ?? ?imformation_func = update_information ?? ?extra_args = {'updated' : now() } information_func( ?? ?name = person.name, ?? ?age = person.name, ?? ?address = person.address, ?? ?**extra_args )
4. 合理使用三元表達(dá)式
使用普通的if / else
語句 代碼可讀性通常更好。
對于三元表達(dá)式只處理簡單的邏輯分支即可。
language = "python" if you.favor("dynamic") else "golang"
5. 常見技巧
5.1德摩根定律
對于下面的代碼,很難第一時間 get 到邏輯關(guān)系。
# 如果用戶沒有登錄或者用戶沒有使用 chrome,拒絕提供服務(wù) if not user.has_logged_in or not user.is_from_chrome: ? ? return "our service is only available for chrome logged in user"
而使用德摩根定律。
not A or not B = not (A and B)
, 代碼讀起來會容易很多。
if not (user.has_logged_in and user.is_from_chrome): ? ? return "our service is only available for chrome logged in user"
5.2自定義類的魔法方法
python提供了跟多自定義類的魔法方法,我們可以利用它門,讓我們的代碼更加pythonic
。
下面的代碼用到了len()
函數(shù)。
class UserCollection(object): ? ? def __init__(self, users): ? ? ? ? self._users = users users = UserCollection([piglei, raymond]) if len(users._users) > 0: ? ? print("There's some users in collection!")
通過給類自定義魔法方法,分支條件變得更加簡單。
并且可以自己控制魔法方法的返回值。
class UserCollection: ? ? def __init__(self, users): ? ? ? ? self._users = users ? ? def __len__(self): ? ? ? ? return len(self._users) users = UserCollection([piglei, raymond]) # 定義了 __len__ 方法后,UserCollection 對象本身就可以被用于布爾判斷了 if users: ? ? print("There's some users in collection!")
5.3在條件判斷中使用 all() / any()
- all (x) : x 中所有對象都為真時返回 True, 否則 False
- any (x): 只要 x 中一個對象為真時返回 True, 否則 False
def all_numbers_gt_10(numbers): ? ? """僅當(dāng)序列中所有數(shù)字大于 10 時,返回 True ? ? """ ? ? if not numbers: ? ? ? ? return False ? ? for n in numbers: ? ? ? ? if n <= 10: ? ? ? ? ? ? return False ? ? return True
使用all ( )
內(nèi)建函數(shù),再配合生成器表達(dá)式。
def all_numbers_gt_10_2(numbers): ? ? return bool(numbers) and all(n > 10 for n in numbers)
5.4使用 try/while/for 中 else 分支
def do_stuff(): ? ? first_thing_successed = False ? ? try: ? ? ? ? # ... ? ? ? ? first_thing_successed = True ? ? except Exception as e: ? ? ? ? # ... ? ? ? ? return ? ? # 僅當(dāng) first_thing 成功完成時,做第二件事 ? ? if first_thing_successed: ? ? ? ? return do_the_second_thing()
其實,我們可以用更簡單的方法達(dá)到同樣的效果:
def do_stuff(): ? ? try: ? ? ? ? # ... ? ? except Exception as e: ? ? ? ? # ... ? ? ? ? return ? ? else: ? ? ? ? return do_the_second_thing()
在 try
的語句塊后面加上 else
分支。
類似的 for / while 也支持 else 分支。
6. 常見陷阱
6.1與 None 值得比較
在 python 中, == 與 is 兩種比較方法有根本的區(qū)別。
-
==
: 僅比較兩者的值是否一致 -
is
: 比較兩者是否指向內(nèi)存中的同一份地址。
但是 None 在 python 中是一個單例對象,如果要判斷某個變量是否為 None 要用 is, 只有 is 才嚴(yán)格意義上表示某個變量是否為None
5.2and 和 or 的運算優(yōu)先級
and 的優(yōu)先級大于 or
即使執(zhí)行的優(yōu)先級如我們想要的一致,也要采取額外括號的方式讓代碼更清晰。
(True or False) and False # False True or False and False # True
此外:
c and a or b 不是總能給出正確的結(jié)果。只有當(dāng) a 與 b 的布爾值為真時,這個表達(dá)式才正常工作,因為邏輯運算的短路特性。
原文鏈接:https://blog.csdn.net/weixin_46442179/article/details/123534172
相關(guān)推薦
- 2021-12-14 常用時間處理方法
- 2023-06-19 Python進(jìn)行文件處理的示例詳解_python
- 2022-07-19 字符數(shù)組,字符串及其操作函數(shù),指針
- 2022-09-05 Shiro 和 Spring Security 的比較
- 2022-10-03 react項目升級報錯,babel報錯,.babelrc配置兼容等問題及解決_React
- 2022-09-20 linux系統(tǒng)下用.sh文件執(zhí)行python命令的方法_linux shell
- 2021-12-01 Android?NDK開發(fā)(C語言--聯(lián)合體與枚舉)_Android
- 2022-09-17 詳解React?如何防止?XSS?攻擊論$$typeof?的作用_React
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支