【问题标题】:Use variables as keywords for functions with pre-defined keywords (Python)使用变量作为具有预定义关键字的函数的关键字 (Python)
【发布时间】:2016-09-16 20:04:10
【问题描述】:

我正在尝试创建一个简单的函数,允许用户输入将更改日期时间对象的值的基本信息,我想找到一种方法,通过使用变量使其尽可能干净作为关键字。这可以很容易地以不同的方式完成,但我认为知道如何替换预设关键字会很有用。

datetime 对象有一个 .replace() 方法,可以将任何时间值作为关键字:

datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])

但我想让用户指定多少时间(例如,2 天;4 小时;1 个月)。

我正在尝试用存储在 time_type 变量中的任何用户输入替换上述任何关键字,直到“分钟”,但我得到“TypeError: ' time_type' 是此函数的无效关键字参数"。

    start_time = datetime.datetime(2016, 09, 16, 15, 30)

    def change_time(integer, time_string):
        time_type = time_string.replace("s","")  # de-pluralizes input
        new_time = getattr(start_time, time_type) + integer
        print(start_time.replace(time_type=new_time))

    change_time(2, "days")

这应该会打印出新的 start_time,即 (2016, 09, 18, 15, 30),但我只是得到一个错误。

【问题讨论】:

标签: python datetime


【解决方案1】:

Python 允许您将数据存储在字典中,最后将它们解压缩为不同函数的关键字参数。

对于你想做的事情,最好的方法是使用 kwargs。

replacement_info = {'day': 2, 'month': 9, ...}

new_time = start_time.replace(**replacement_info)

请注意与您所做的不同之处。将time_type 直接传递给replace,将导致replace 被调用并带有time_type 参数,设置为2,这是未定义的(因为它不在replace 接受的参数列表中)

您必须像 **{time_type: 2} 一样将其传递给 replace 函数,这样,replace 将接收 time_type 的解释值,即天,作为输入。

所以你需要改变

print(start_time.replace(time_type=new_time))

print(start_time.replace(**{time_type:new_time})

【讨论】:

    【解决方案2】:

    您不能替换不是您编写的函数的关键字参数。调用类似的函数时:

    f(a=b)
    

    a 的值不会作为参数发送给f。而是发送b 的值,并将该值设置为f's 参数列表定义中的参数a。如果f 没有定义a 参数(因为datetime.replace 没有定义time_type 参数),您将得到invalid keyword argument 异常。

    正如其他人所说,将动态关键字参数传递给函数使用**kwargs 表示法。

    【讨论】:

      【解决方案3】:

      把最后一行改成这样:

      year = start_time.year
      month = start_time.month
      day = start_time.day
      hour = start_time.hour
      minute = start_time.minute
      second = start_time.second
      microsecond = start_time.microsecond
      exec(time_type + '='+str(new_time))
      print(start_time.replace(year, month, day, hour, minute, second, microsecond)
      

      【讨论】:

        猜你喜欢
        • 2018-12-28
        • 2022-01-05
        • 1970-01-01
        • 1970-01-01
        • 2015-10-26
        • 1970-01-01
        • 2019-12-01
        • 2017-01-15
        • 1970-01-01
        相关资源
        最近更新 更多