Python Switch 重复调用小问题

栏目: Python · 发布时间: 5年前

内容简介:大家都知道Python 中没有Switch 关键词,如果写一堆if-elif-else 非常不美观,通常的做法是使用字典,今天遇到一个小问题,如下:写完测试一下,发现字典里面每个函数都会被执行一遍,有点蒙,不过马上就明白了,但是一时不知道该如何解决,Google 下找到了解决方式:改一下:

大家都知道 Python 中没有Switch 关键词,如果写一堆if-elif-else 非常不美观,通常的做法是使用字典,今天遇到一个小问题,如下:

class Recource(object):
   def do(self, provider, action):
       return {
         'aliyun':{
             'create': self.__create__(),
             'update': self.__update__(),
             ...
             },
         'aws': ...
        }[provider][action]

写完测试一下,发现字典里面每个函数都会被执行一遍,有点蒙,不过马上就明白了,但是一时不知道该如何解决,Google 下找到了解决方式: Pythonic switch within class ,

改一下:

class Recource(object):
   def do(self, provider, action):
       return {
         'aliyun':{
-            'create': self.__create__(),
-            'update': self.__update__(),
+            'create': lambda: self.__create__(),
+            'update': lambda: self.__update__(),
             ...
             },
         'aws': ...
-       }[provider][action]
+       }[provider][action]()

原来如此,简单快捷,学习了,又一次面向Stack Overflow 编程 :P。


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

An Introduction to the Analysis of Algorithms

An Introduction to the Analysis of Algorithms

Robert Sedgewick、Philippe Flajolet / Addison-Wesley Professional / 1995-12-10 / CAD 67.99

This book is a thorough overview of the primary techniques and models used in the mathematical analysis of algorithms. The first half of the book draws upon classical mathematical material from discre......一起来看看 《An Introduction to the Analysis of Algorithms》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具