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

Python中函数作为参数传入报错,求原因及解决方法

问题分析与解决

错误原因

你调用return_real时传的第二个参数是get_two(),这会立即执行get_two函数并返回字符串'two'。但return_real的第二个参数function需要接收的是可调用的函数对象,不是字符串。当函数内部执行function()时,本质是试图对字符串'two'执行调用操作,而字符串不支持这种操作,所以触发TypeError: 'str' object is not callable。

修正方法

把调用时的get_two()改成get_two,也就是传递函数本身,而不是函数执行后的结果:

def get_two():
    return 'two'

def get_three():
    return 'three'

def return_real(text, function):
    my_string = text + function()
    return my_string

# 传递函数对象而非函数执行结果
print(return_real('one', get_two))

修正后的代码运行后,会输出你预期的onetwo。

内容的提问来源于stack exchange,提问作者Anthony Q Phan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 04:10:34