厭倦編碼的你
在編碼初期,我們因為學(xué)會一種句式,掌握一種語法而歡喜。但工作時間久了,卻漸漸發(fā)現(xiàn),日常的編碼中更多的是讓人厭煩的選擇邏輯、循環(huán)遍歷,在加上最擅長的CTRL+C && CTRL+V。你是否想過改變一下自己的代碼風(fēng)格?
萬年不變的if.else
提到日常編碼,可能我們用到最多的就是if else了,可偏偏Python中沒有case when,那么文藝青年的我們,該如何讓if else變得與眾不同呢?不如看看下面的例子...
假如你是一家酒店的前臺,酒店分設(shè)了標(biāo)間、商務(wù)間、情侶主題房?,F(xiàn)在根據(jù)客人的選擇,你需要告知他對應(yīng)的金額。該如何操作?
是不很多人馬上開始這么寫了:
def show_price_list(user_choice):
if user_choice.lower() == 'single':
print(150)
elif user_choice.lower() == 'business':
print(300)
elif user_choice.lower() == 'couple':
print(500)
else:
print("未找到你所需要的房間類型")
show_price_list('couple')
代碼沒毛病,但不覺得重復(fù)感太強(qiáng)嗎?我們能否換個方式來編碼,like this:
PRICES = {'single': 150, 'business': 300, 'couple': 500}
def show_price_list(user_choice):
print(PRICES.get(user_choice.lower(), "未找到你所需要的房間類型"))
show_price_list('couple')
不管從代碼量,還是代碼整潔度來說,是否有一個顯著的提升??珊芏嗳擞终f了,你這是單行打印,如果我需要針選擇的結(jié)果去調(diào)用不同的方法呢?
通過字典執(zhí)行方法
答案是,你依然可以這么做,舉個例子:
首先,我們定義一個 play_list.py
def work():
print('Oh,no...我要開始工作了。')
def play():
print("Dota魚塘局,快來五連坐...")
def drink():
print("沒有撤退可言,不醉不歸!")
下來,我們創(chuàng)建一個play_choice.py,并通過導(dǎo)入play_list的方式,來進(jìn)行方法的選擇:
from play_list import work, play, drink
choices = {'work': work, 'play': play, 'drink': drink}
def to_do(user_choice):
try:
choices.get(user_choice)()
except TypeError:
print("你玩的太溜,我的字典里沒有...")
to_do('dance')
to_do('drink')
output:
你玩的太溜,我的字典里沒有...
沒有撤退可言,不醉不歸!
包的導(dǎo)入“BUG”
在文章的結(jié)尾,我們來分享一個pyhton的導(dǎo)入bug!
很多人都知道Python有一個all方法,他們的回答一般都是,all用來作為導(dǎo)入限制,禁止導(dǎo)入不在all方法內(nèi)的模塊。這么說對么?錯誤!
讓我們來看看正確的說明:
all affects the from <module> import * behavior only. Members that are not mentioned in all are still accessible from outside the module and can be imported with from <module> import <member>.
all方法只限制那些from module import *的行為,當(dāng)我明確的from module import member時,并不會阻止!拿我們剛才的例子來說:
__all__ = ['work','play']
def work():
print('Oh,no...我要開始工作了。')
def play():
print("Dota魚塘局,快來五連坐...")
def drink():
print("沒有撤退可言,不醉不歸!")
當(dāng)我們使用如下方式去調(diào)用:
from play_list import *
choices = {'work': work, 'play': play, 'drink': drink}
報錯: NameError: name 'drink' is not defined
但當(dāng)我們明確的寫出具體的方法是,一切正常
from play_list import work, play, drink
choices = {'work': work, 'play': play, 'drink': drink}
好了,今天的內(nèi)容就到這里,明天拿all去考考你的朋友,看看他對這個概念是否理解透徹吧!
The End
期待你關(guān)注我的公眾號清風(fēng)Python,如果你覺得不錯,希望能動動手指轉(zhuǎn)發(fā)給你身邊的朋友們。
我的github地址:https://github.com/BreezePython