繁体   English   中英

如何将可选参数传递给python中的函数?

[英]how to pass optional parameters into a function in python?

我有一个函数,我想传递两个可选参数。 我已经通读了,但是以某种方式我无法使它工作。

我在这里想念什么?

我有这样的东西

def json_response_message(status, message, option_key, option_value):
    data = {
        'status': status,
        'message': message,
    }
    if option_key:
        data[option_key] = option_value
    return JsonResponse(data)

最后两个参数我希望它是可选的。

我已经看到可以做到

def json_response_message(status, message, option_key='', option_value=''):

但是我并不是真的想这样做,而是看到有一种方法可以传递*args and **kwargs但是它无法使它工作。

我只是停留在放置可选参数,但不确定如何调用和使用它们。 我通读了一些帖子,可以轻松地通过使用for loop来完成它并调用它for loop但是以某种方式它对我不起作用

def json_response_message(status, message, *args, **kwargs):
    data = {
        'status': status,
        'message': message,
    }

    return JsonResponse(data)

我想在我的数据返回中添加额外的参数,例如...

    user = {
        'facebook': 'fb',
        'instagram': 'ig'
    }

    return json_response_message(True, 'found', 'user', user)

我想您想要这样的东西:

def json_response_message(status, message, options=()):
    data = {
    'status': status,
    'message': message,
    }

    # assuming options is now just a dictionary or a sequence of key-value pairs
    data.update(options)

    return data

您可以像这样使用它:

user = {
    'facebook': 'fb',
    'instagram': 'ig'
}
print(json_response_message(True, 'found', user))
def json_response_message(status, message, *args):

    #input validation
    assert len(args) == 0 or len(args) == 2

    # add required params to data
    data = {
    'status': status,
    'message': message,
    }

    # add optional params to data if provided
    if args:
      option_key = args[0]
      option_value = args[1]
      data[option_key] = option_value      

    return data

print(json_response_message(True, 'found', 'user', user))

{'user':'jim','status':true,'message':'found'}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM