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

如何让自动生成的代码返回类对象而非字符串元素的列表?

解决生成代码中返回类对象列表的问题

问题场景

编写脚本通过两个参数自动生成文件:

  1. newName:类名前缀(比如SquadState中的Squad)
  2. 追加字符串列表:比如['.DOWN', '.UP']

期望生成的get_state_order函数返回类属性组成的列表(如[SquadState.DOWN, SquadState.UP]),但实际生成的是字符串列表['SquadState.DOWN', 'SquadState.UP']。修改时触发TypeError: 'str' object is not callable错误,相关代码及报错如下:

生成文件的代码片段:

file = f"""
....
def get_state_order() -> list[{exercise_name.capitalize()}State]:
    \"\"\"Returns the order of the states of the exercise\"\"\"
    return {list(newName + abc for abc in states)}
....
"""

报错信息:

Traceback (most recent call last):
  File "/Users/work/PycharmProjects/KI/et_ki/models/exercises/automatisierung.py", line 91, in <module>
    create_exercise_file(exercise_name, states)
  File "/Users/work/PycharmProjects/KI/et_ki/models/exercises/automatisierung.py", line 67, in create_exercise_file
    return {list(exercise_name(newName + abc) for abc in states)}
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'str' object is not callable

错误原因

  1. 原代码中,list(newName + abc for abc in states)会生成一个字符串列表,拼到生成的代码里后,return语句就变成返回字符串列表,而非类属性。
  2. 修改时误将字符串类型的exercise_name当作函数调用(exercise_name(newName + abc)),导致触发"str对象不可调用"的错误。

解决方案

不需要在生成脚本中做类型转换,而是直接构建出正确的代码字符串,让生成的get_state_order函数直接返回类属性列表:

  1. 先拼接出每个类属性的字符串(比如SquadState.DOWN),再用逗号连接成列表格式的字符串。
  2. 将这个字符串直接插入到生成的代码的return语句中。

修改后的代码示例:

# 先构建类属性的字符串列表,再拼接成符合代码语法的格式
state_list_str = ', '.join(f"{newName}{abc}" for abc in states)

file = f"""
....
def get_state_order() -> list[{exercise_name.capitalize()}State]:
    \"\"\"Returns the order of the states of the exercise\"\"\"
    return [{state_list_str}]
....
"""

这样生成的代码中,return语句会是return [SquadState.DOWN, SquadState.UP],执行时自然返回类属性组成的列表,而非字符串列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 07:11:10