将if-elseif语句转换为字典 [英] Turn if-elseif statements into dictionary

查看:135
本文介绍了将if-elseif语句转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码进行RESTful调用服务器:

I have the following code for making a RESTful call to a server:

def request(self, request, account_id, user):

    if request is 'get_id':
        #Get user from id
        result = requests.get(api_root + "/accounts/" + account_id + "/users/" + user, headers=self.headers)

    elif request is 'get_username':
        #Get user from username
        result = requests.get(api_root + "/accounts/" + account_id + "/users?username=" + user, headers=self.headers)

    elif request is 'get_email':
        #Get user from username
        result = requests.get(api_root + "/accounts/" + account_id + "/users?email=" + user, headers=self.headers)

    elif request is 'post':
        #Add user to new account
        result = requests.post(api_root + '/accounts/' + account_id + '/users', data=json.dumps(user), headers=self.headers)

    elif request is 'delete':
        #Delete user from account
        result = requests.delete(api_root + "/accounts/" + account_id + "/users/" + user, headers=self.headers)

    #Throw exception if non-200 response
    result.raise_for_status()

    #Print request result / status
    print "\nRequest " + request + " Result: " + result.text + "\nStatus: " + str(result.status_code)

    return result

我知道这很丑,我想把它改成字典,如:

I know this is ugly and I wanted to change it into a dictionary, something like:

def request(self, request, account_id, user):
    url = api_root + "/accounts/" + account_id

    function_dictionary = {}
    function_dictionary['get_id']       = requests.get(url + "/users/" + user, headers=self.headers)
    function_dictionary['get_username'] = requests.get(api_root + "/accounts/" + account_id + "/users?username=" + user, headers=self.headers)
    function_dictionary['get_email']    = requests.get(api_root + "/accounts/" + account_id + "/users?email=" + user, headers=self.headers)
    function_dictionary['delete']       = requests.delete(url + "/users/" + user, headers=self.headers)
    function_dictionary['post']         = requests.post(url + '/users', data=json.dumps(user), headers=self.headers)  

    result = function_dictionary.get(request)

    #Throw exception if non-200 response
    result.raise_for_status()
    return result

我还有一种感觉,我正在做错误的方式。有没有人可以告诉我,如果Python中的/ elseif语句是正确的方法?

I still have a feeling I am going about it the wrong way. Can anybody tell me what the proper method to approach if / elseif statements in Python is?

谢谢!

推荐答案

使用 dict 替换如果:elif:循环当然是Pythonic,但请注意,在您的示例中,您为您存储在字典中的每个案例调用 requests.get 等,即字典值是那些电话。

Using a dict to replace if: elif: loops is certainly Pythonic, but note that in your example you are calling requests.get etc for every case you store in the dictionary, i.e. the dictionary values are the results of those calls.

另一种方法是在字典中分别存储函数和参数:

An alternative would be to store function and arguments separately in the dictionary:

function_dict = {'get_id': (requests.get, # function
                            (url + "/users/" + user,), # tuple of arguments  
                            {'headers': self.headers}), # dict of keyword args
                 ...}

现在可以使用

func, args, kwargs = function_dict[request]
result = func(*args, **kwargs)

另外,请注意,使用比较字符串是是坏主意(虽然它有时工作);最好使用 ==

Also, note that comparing strings using is is a bad idea (although it sometimes works); it is better to use ==:

if request == 'get_id':

这篇关于将if-elseif语句转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆