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

如何实现可动态适配不同子类的EnhancedUserInput类?

实现EnhancedUserInput类结构的思路与示例

我来帮你梳理这个类结构的实现方案,用Python为例,咱们可以通过基类+子类继承的方式来实现,同时结合数据类让结构更清晰易维护:

1. 定义基类EnhancedUserInput

先把所有输入类型共有的变量放到基类里,比如输入ID、提示文本、是否必填这些核心属性,再加一个标识输入类型的属性,方便运行时判断当前实例属于哪个子类:

from dataclasses import dataclass
from abc import ABC

@dataclass
class EnhancedUserInput(ABC):
    # 所有输入类型共有的变量
    input_id: str
    prompt_text: str
    is_required: bool = True
    
    @property
    def input_type(self) -> str:
        # 返回当前输入类型的标识,子类可按需重写
        return self.__class__.__name__

这里用ABC(抽象基类)确保基类不能被直接实例化,dataclass则简化了属性的定义和初始化逻辑。

2. 实现MultipleChoice子类

这个子类需要额外的min_selection、max_selection,以及一个带自有变量的选项列表。咱们可以给选项单独定义一个数据类Option来封装它的自有属性:

@dataclass
class Option:
    # Option的自有变量
    option_id: str
    label: str
    is_default: bool = False
    description: str = ""  # 可选的额外说明属性

@dataclass
class MultipleChoice(EnhancedUserInput):
    # MultipleChoice专属变量
    min_selection: int = 1
    max_selection: int = 1
    options: list[Option] = None
    
    def __post_init__(self):
        # 初始化时确保options不为空列表,避免后续报错
        if self.options is None:
            self.options = []

__post_init__方法用来处理默认值的初始化,防止options为None的情况影响后续操作。

3. 实现ExplicitAgreement子类

比如这个子类用于需要用户明确同意的场景,额外属性可以包括同意文本、是否需要勾选框等:

@dataclass
class ExplicitAgreement(EnhancedUserInput):
    # ExplicitAgreement专属变量
    agreement_text: str
    requires_checkbox: bool = True
    show_details_link: bool = False

4. 运行时适配与使用

现在你可以根据需求在运行时动态创建不同子类的实例,比如:

# 创建一个多选输入实例
color_options = [
    Option("red", "红色"),
    Option("blue", "蓝色", is_default=True),
    Option("green", "绿色", description="清新色调")
]
color_input = MultipleChoice(
    input_id="favorite_color",
    prompt_text="请选择你喜欢的颜色(可多选)",
    min_selection=1,
    max_selection=2,
    options=color_options
)

# 创建一个同意条款的输入实例
terms_agreement = ExplicitAgreement(
    input_id="terms_agree",
    prompt_text="请阅读并同意以下条款",
    agreement_text="我同意网站的隐私政策与服务条款",
    show_details_link=True
)

# 运行时判断输入类型并做对应处理
def process_input(input_instance: EnhancedUserInput):
    if input_instance.input_type == "MultipleChoice":
        print(f"处理多选输入:{input_instance.prompt_text},可选范围{input_instance.min_selection}-{input_instance.max_selection}项")
    elif input_instance.input_type == "ExplicitAgreement":
        print(f"处理同意输入:{input_instance.agreement_text}")

process_input(color_input)
process_input(terms_agreement)

额外优化建议

  • 如果需要更灵活的运行时适配,可以用工厂模式封装实例创建逻辑,比如写一个InputFactory类,根据输入类型参数返回对应的子类实例。
  • 可以给基类添加抽象方法(比如validate_input),让每个子类实现自己的输入验证逻辑,确保用户输入符合该类型的规则。

内容的提问来源于stack exchange,提问作者C. Dodds

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:47:08