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

在字典中存储类时调用context.call遇类型错误,求解决办法

解决context.call字典映射的类型错误问题

Hey there! I totally get why you'd want to ditch those messy if-else chains—using a dictionary for handler mappings is way cleaner. Let's fix that type error you're seeing right away.

核心结论:字典的值要存类本身

The context.call() method expects to receive a class object (not an instance of the class, not a string name of the class) as its argument. So your dictionary should map user input phrases directly to the actual class definitions you've created for each department.

具体实现示例

First, make sure you've imported all your department handler classes:

from your_project_modules import ShowComp, ShowEE, ShowBio, ShowMath

Then define your mapping dictionary, with class objects as the values:

# Map user input triggers to corresponding department classes
department_handler_map = {
    "show me computer engineering": ShowComp,
    "show me electrical engineering": ShowEE,
    "show me biology": ShowBio,
    "show me mathematics": ShowMath,
    # Add more department mappings here as needed
}

When handling user input, just look up the class in the dictionary and pass it straight to context.call():

user_input = ...  # Get the user's input string here

if user_input in department_handler_map:
    # Pass the class directly to context.call
    return context.call(department_handler_map[user_input])
else:
    # Handle unrecognized input
    return "Sorry, I don't have information for that department yet."

为什么之前会触发类型错误?

If you were storing strings (like "ShowComp") or already-instantiated objects (like ShowComp()) in the dictionary, context.call() would throw a type error—it can't work with those types. It needs the raw class to create a new instance and handle the conversation flow properly.

额外优化小技巧

If you want to handle multiple variations of user input (e.g., "comp eng" instead of "computer engineering"), you can map multiple keys to the same class:

department_handler_map = {
    "show me computer engineering": ShowComp,
    "comp eng": ShowComp,
    "computer dept": ShowComp,
    # ... other mappings
}

内容的提问来源于stack exchange,提问作者Safa Elmalı

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:53:29