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

Python类代码输入a/b/c触发TypeError: 'str' object is not callable求助

错误原因分析

你输入的a/b/c是字符串类型,执行choice1()相当于尝试调用一个字符串对象——但字符串本身不是可调用的(只有函数、类这类对象才能用()触发调用),所以抛出TypeError: 'str' object is not callable错误。

解决方法

这里提供两种可靠的修复方式:

方法一:用字典建立字符串到类的映射(推荐)

通过字典明确关联输入字符串和对应的类,安全性更高,也更易维护:

class a:
    name = "option a"
class b:
    name = "option b"
class c:
    name = "option c"

# 建立输入字符串与类的映射关系
class_mapping = {
    "a": a,
    "b": b,
    "c": c
}

choice1 = input("input: ")
# 根据输入获取对应的类
target_class = class_mapping.get(choice1)
if target_class:
    print(target_class.name)
else:
    print("无效输入,请输入a、b或c")

方法二:通过全局命名空间获取类

利用globals()函数直接从全局命名空间中取出类,但必须先做输入验证,避免访问到其他全局对象:

class a:
    name = "option a"
class b:
    name = "option b"
class c:
    name = "option c"

choice1 = input("input: ")
# 先验证输入是否在允许范围内
if choice1 in ["a", "b", "c"]:
    target_class = globals()[choice1]
    print(target_class.name)
else:
    print("无效输入,请输入a、b或c")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 05:31:17