You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python函数内将参数传递给调用的方法时触发TypeError如何解决

问题排查与修复方案

错误原因

  • datetime.timedelta(string=integer)的写法不符合Python语法逻辑:此处的string会被Python识别为timedelta的固定参数名,而非你定义的存储参数类型的变量,而timedelta没有名为string的合法入参,因此触发TypeError。
  • Python不支持直接将变量作为关键字参数的参数名写在入参列表中,要实现动态关键字参数传递需要用字典解包语法。

修复方法

将动态参数组装为字典,通过**操作符解包后传给datetime.timedelta即可,修复后代码如下:

import datetime
    
starter = datetime.datetime(2015, 10, 21, 16, 29)
    
def time_machine(integer, string):
    if string == 'years':
        string = 'days'
        integer *= 365
    return starter - datetime.timedelta(**{string: integer})

效果验证

  • 调用time_machine(1, 'years'),返回结果为datetime.datetime(2014, 10, 21, 16, 29),符合预期。
  • 调用time_machine(30, 'minutes'),返回结果为datetime.datetime(2015, 10, 21, 15, 59),符合预期。

内容的提问来源于stack exchange,提问作者Simon Lindsay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 17:36:03