厌倦了if.else的你,能否考虑换一种选择结构?

举报
技术火炬手 发表于 2020/06/10 10:53:32 2020/06/10
【摘要】 你是否想过改变一下自己的代码风格?

image.png

image.png

在编码初期,我们因为学会一种句式,掌握一种语法而欢喜。但工作时间久了,却渐渐发现,日常的编码中更多的是让人厌烦的选择逻辑、循环遍历,在加上最擅长的CTRL+C && CTRL+V。你是否想过改变一下自己的代码风格?

image.png

提到日常编码,可能我们用到最多的就是if else了,可偏偏Python中没有case when,那么文艺青年的我们,该如何让if else变得与众不同呢?不如看看下面的例子... 假如你是一家酒店的前台,酒店分设了标间、商务间、情侣主题房。现在根据客人的选择,你需要告知他对应的金额。该如何操作?是不很多人马上开始这么写了:

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')

代码没毛病,但不觉得重复感太强吗?我们能否换个方式来编码,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')

不管从代码量,还是代码整洁度来说,是否有一个显著的提升。可很多人又说了,你这是单行打印,如果我需要针选择的结果去调用不同的方法呢?

image.png

答案是,你依然可以这么做,举个例子:首先,我们定义一个 play_list.py

def work():
    print('Oh,no...我要开始工作了。')

def play():
    print("Dota鱼塘局,快来五连坐...")

def drink():
    print("没有撤退可言,不醉不归!")

下来,我们创建一个play_choice.py,并通过导入play_list的方式,来进行方法的选择:

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:
你玩的太溜,我的字典里没有...
没有撤退可言,不醉不归!

image.png

在文章的结尾,我们来分享一个pyhton的导入bug!很多人都知道Python有一个__all__方法,他们的回答一般都是,__all__用来作为导入限制,禁止导入不在all方法内的模块。这么说对么?错误!让我们来看看正确的说明:

__all__ affects the fromimport * behavior only. 
Members that are not mentioned in __all__ are still 
accessible from outside the module and can be imported with fromimport.

__all__方法只限制那些from module import *的行为,当我明确的from module import member时,并不会阻止。拿我们刚才的例子来说:

__all__ = ['work','play']

def work():
    print('Oh,no...我要开始工作了。')

def play():
    print("Dota鱼塘局,快来五连坐...")

def drink():
    print("没有撤退可言,不醉不归!")

当我们使用如下方式去调用:

from play_list import *

choices = {'work': work, 'play': play, 'drink': drink}

报错:NameError: name 'drink' is not defined

但当我们明确的写出具体的方法是,一切正常

from play_list import work, play, drink

choices = {'work': work, 'play': play, 'drink': drink}

好了,今天的内容就到这里,明天拿__all__去考考你的朋友,看看他对这个概念是否理解透彻吧!

本文转自“清风Python”公众号

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。