使用变量作为函数的关键字参数

时间:2018-07-20 05:06:21

标签: python function variables parameter-passing keyword-argument

我有以下代码:

quantity_of_units = int(funding_time_left.split[0])
unit_of_measurement = funding_time_left.split()[1]
now = datetime.datetime.now()
if unit_of_measurement == 'days':
    end = (now + timedelta(days=quantity_of_units)).strftime('%Y-%m-%d')
elif unit_of_measurement == 'hours':
    end = (now + timedelta(hours=quantity_of_units)).strftime('%Y-%m-%d')
else: # unit_of_measure == 'minutes'
    end = (now + timedelta(minutes=quantity_of_units)).strftime('%Y-%m-%d')
funding.append([aeles.get_attribute('href'), end])

我想知道是否可以使用变量(unit_of_measurement)作为关键字参数(dayshoursminutes)?

如果确实有可能,我可以完全废弃if elif else块并将其全部变成一行。下面是我希望做的。

quantity_of_units = int(funding_time_left.split[0])
unit_of_measurement = funding_time_left.split()[1]
now = datetime.datetime.now()
end = (now + timedelta(unit_of_measurement=quantity_of_units)).strftime('%Y-%m-%d')
funding.append([aeles.get_attribute('href'), end])

1 个答案:

答案 0 :(得分:1)

您可以使用**在参数中解包dict,将其设置为关键字参数。

timedelta(**{unit_of_measurement: quantity_of_units})

之所以起作用,是因为它解压缩到:

timedelta(<unit_of_measurement>=quantity_of_units)

<unit_of_measurement>minutessecondsdays ...


因此,您可以将if... elif... else...语句替换为:

end = (now + timedelta(**{unit_of_measurement: quantity_of_units})).strftime('%Y-%m-%d')