Skip to main content
 首页 » 编程设计

python之函数中的 None 是什么意思/可选字段

2024年12月31日8虾米哥

我正在尝试使用下面的功能。大多数情况下,当我调用此函数时,我只是传入 report_type,但一些报告调用需要 start_date。问题

  1. 函数定义中的None是否表示该字段是可选的

    def request_report(self, report_type, start_date=None, end_date=None, marketplaceids=()): 
    data = dict(Action='RequestReport', 
                ReportType=report_type, 
                StartDate=start_date, 
                EndDate=end_date) 
    data.update(utils.enumerate_param('MarketplaceIdList.Id.', marketplaceids)) 
    return self.make_request(data) 
    
  2. 我通常使用以下行之一调用该函数,具体取决于我是否传递开始日期。除了为每种请求类型设置一系列“if”语句之外,是否有一种很好的方法来调用此函数并且仅在填充特定变量时才传递该变量?随着时间的推移,我将添加更多可选参数,并且不再需要一个巨大的“if”语句

    requested_report=report_api.request_report(report_type=report_name, start_date=starting_date) 
    requested_report=report_api.request_report(report_type=report_name) 
    

请您参考如下方法:

=... 部分为参数提供了一个默认值。这里是 None,这意味着调用函数时该参数是可选的。如果不指定,则使用默认值。参见 Default Argument Values在 Python 教程中,以及 reference documentation for function definitions :

When one or more parameters have the form parameter = expression, the function is said to have “default parameter values.” For a parameter with a default value, the corresponding argument may be omitted from a call, in which case the parameter’s default value is substituted.

当调用这样的函数时,您可以将与默认值相同的值传递给这个没有区别的特定函数;所以当没有starting_date时,可以传入None:

start_date = starting_date or None  # when determining the starting date, default to None 
requested_report=report_api.request_report( 
    report_type=report_name, 
    start_date=starting_date 
) 

另一种选择是在字典中设置任何可选的关键字参数,然后使用 ** 调用语法将它们传递给 unpack the dictionary as keyword arguments :

kwargs = {} 
if ...:  # test that decides if start_date is needed 
    kwargs['start_date'] = starting_date  # expression to set the start date 
 
requested_report=report_api.request_report( 
    report_type=report_name, **kwargs) 

kwargs 字典可以为空。