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

Python实现可调用递减索引生成器,解决报告遍历匹配场景报错

问题分析与解决方案

错误原因

报错核心:IndexGenerator1.returnIndex方法中,你传入了TestNameReportFile实例作为参数,随后尝试访问self.index——但此处的self是传入的TestNameReportFile对象,而非IndexGenerator1自身,而该TestNameReportFile实例并未初始化index属性,因此触发AttributeError。

单场景时程序能运行,大概率是巧合下该实例的index属性被隐式赋值(比如某个分支逻辑不小心设置过),但多场景遍历无此赋值操作,错误便暴露出来。


修复方案

方案1:让索引生成器自身维护状态(推荐)

将IndexGenerator1改为独立维护索引的类,不依赖外部对象属性:

class IndexGenerator1:
    def __init__(self, total_reports):
        # 初始化时传入报告总数,从最后一个索引开始
        self.current_idx = total_reports - 1

    def returnIndex(self):
        if self.current_idx >= 0:
            result = self.current_idx
            self.current_idx -= 1
            return result
        # 无更多索引时返回-1或抛出异常,按需调整
        return -1

使用方式:遍历报告前初始化生成器,传入报告列表长度,之后每次调用returnIndex()获取递减索引:

# 假设report_list是你的报告列表
oIndexGenerator = IndexGenerator1(len(report_list))

# 在TestNameReportFile.getReportPath中调用
self.index = oIndexGenerator.returnIndex()

方案2:确保TestNameReportFile先初始化index属性

若一定要让生成器操作外部对象属性,先在TestNameReportFile构造方法中初始化index:

class TestNameReportFile:
    def __init__(self):
        # 初始化index属性,初始值根据业务逻辑设置
        self.index = 0

随后修改IndexGenerator1.returnIndex逻辑,明确操作传入对象的属性:

class IndexGenerator1:
    def __init__(self, start_idx):
        self.start_idx = start_idx

    def returnIndex(self, report_obj):
        # 实现递减逻辑,比如从start_idx开始逐次减1
        if report_obj.index == 0:
            report_obj.index = self.start_idx
        else:
            report_obj.index -= 1
        return report_obj.index

简化实现思路

无需单独写类生成递减索引,用Python内置生成器函数更简洁:

def decrementing_index(total):
    current = total - 1
    while current >= 0:
        yield current
        current -= 1

# 使用示例
report_list = [你的报告列表]
index_gen = decrementing_index(len(report_list))

# 每次遍历获取下一个索引
next(index_gen)  # 返回 len(report_list)-1
next(index_gen)  # 返回 len(report_list)-2
# ...直到返回0后抛出StopIteration,可通过try-except捕获或for循环遍历

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 17:42:38