Python无变量用法

时间:2011-10-19 19:56:35

标签: python

有没有办法简化以下代码:

def get_or_create_user(id, photo=None, first_name=None, last_name=None, nickname=None, organization=None, city=None, country=None):
    ... # save user in the datastore

class UserCreationHandler(webapp.RequestHandler):
    def get(self):
        id = self.request.get('id')
        photo = None
        first_name = None
        last_name = None
        nickname = None
        organization = None
        city = None
        country = None
        if something1:
            # do some calculations
            if something2:
                # do some other calculations
                if something3:
                    # assign id, photo, first_name etc. values 
        get_or_create_user(id, photo, first_name, last_name, nickname, organization, city, country)

我不喜欢这些分配给无。

2 个答案:

答案 0 :(得分:6)

类似的东西:

def get(self):
    id = self.request.get('id')
    user_details = {}
    if something:
        # assign user_details['id'], user_details['photo'], user_details['first_name'] etc. values
    get_or_create_user(id, **user_details)

答案 1 :(得分:3)

看到get_or_create_user使用默认参数设置为None

def get_or_create_user(id, photo=None, first_name=None, last_name=None, nickname=None, organization=None, city=None, country=None):

你可以使用它:

class UserCreationHandler(webapp.RequestHandler):
    def get(self):
        id = self.request.get('id')
        if something:
            # set stuff ...
            # and then call get_or_create_user(...)
        else:
            get_or_create_user(id)