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

Python报错TypeError: 'str' object is not callable的修复求助

问题修复方案

错误原因

你推测的完全正确——报错核心就是operations字典里存的是函数名的字符串(比如"add"),不是函数本身。当你取出这个字符串后试图像调用函数一样执行它,自然会触发TypeError: 'str' object is not callable,因为字符串根本不是可调用对象。

修复方法

方法一:直接在字典中存储函数对象(推荐)

把字典里的字符串值替换成对应的函数本身,这样取出后直接就能调用:

def add(n1, n2):
  return n1 + n2

def subtract(n1, n2):
  return n1 - n2

def multiply(n1, n2):
  return n1 * n2

def divide(n1, n2):
  return n1 / n2

# 直接存函数对象,而非字符串
operations = {
  "+": add,
  "-": subtract,
  "*": multiply,
  "/": divide
}

num1 = int(input("What's the first number?: "))
num2 = int(input("What's the second number?: "))

for operation in operations:
  print(operation)

operation_symbol = input("Pick an operation from the line above: ")

calculation_function = operations[operation_symbol]
answer = calculation_function(num1, num2)

print(f"{num1} {operation_symbol} {num2} = {answer}")

方法二:通过命名空间获取函数(适合必须存字符串的场景)

如果非要在字典里存函数名字符串,可以通过globals()(全局命名空间字典)取出对应的函数:

def add(n1, n2):
  return n1 + n2

def subtract(n1, n2):
  return n1 - n2

def multiply(n1, n2):
  return n1 * n2

def divide(n1, n2):
  return n1 / n2

operations = {
  "+": "add",
  "-": "subtract",
  "*": "multiply",
  "/": "divide"
}

num1 = int(input("What's the first number?: "))
num2 = int(input("What's the second number?: "))

for operation in operations:
  print(operation)

operation_symbol = input("Pick an operation from the line above: ")

# 从全局命名空间中取出对应函数
calculation_function = globals()[operations[operation_symbol]]
answer = calculation_function(num1, num2)

print(f"{num1} {operation_symbol} {num2} = {answer}")

说明

方法一更直接高效,是Python的惯用写法,优先推荐。方法二只适合特殊场景,比如需要动态从字符串映射函数的情况。

内容的提问来源于stack exchange,提问作者oz cem

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:15:37