簡體   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