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

调用cached_property装饰方法报错TypeError:对象不可调用求助

问题分析与修复

核心错误原因

你遇到的TypeError是因为**cached_property装饰的是实例属性,不是可直接调用的类方法**,同时代码在类的初始化、属性调用逻辑上存在多处错误。

具体问题点及修复方案

  1. 缺失必要导入
    代码使用了json模块和cached_property装饰器但未导入,需补充:

    import json
    from propcache import cached_property
    
  2. File类未初始化文件路径
    当前类没有__init__方法,无法将文件路径传入实例,导致open(self, 'r')尝试打开File实例而非路径字符串。需添加初始化逻辑:

    class File:
        def __init__(self, filepath):
            self.filepath = filepath
    
  3. cached_property的使用与调用错误
    @cached_property装饰的是实例属性,需通过类实例访问,而非直接用类调用。同时要修改方法内的文件路径引用:

    @cached_property
    def get_timestamp(self):
        # 用self.filepath替代self,指向传入的文件路径
        with open(self.filepath, 'r') as f:
            timestamps = []
            for line in f:
                row = json.loads(line)
                timestamps.append(row.get("ts"))
        timestamps.sort()
        lowest_timestamp = timestamps[0]
        highest_timestamp = timestamps[-1]
        return lowest_timestamp, highest_timestamp, timestamps
    
  4. 循环逻辑冗余错误
    第一个循环里filename = File()创建了实例但未使用,还覆盖了原有变量,需调整为直接创建File实例并存储:

完整修复后的代码

import os
import json
from propcache import cached_property

class File:
    def __init__(self, filepath):
        self.filepath = filepath

    @cached_property
    def get_timestamp(self):
        with open(self.filepath, 'r') as f:
            timestamps = []
            for line in f:
                row = json.loads(line)
                ts = row.get("ts")
                if ts is not None:  # 避免None值干扰排序
                    timestamps.append(ts)
        if not timestamps:
            return None, None, []  # 处理空文件场景,防止索引报错
        timestamps.sort()
        lowest_timestamp = timestamps[0]
        highest_timestamp = timestamps[-1]
        return lowest_timestamp, highest_timestamp, timestamps

# 确保orderbook是已定义的合法目录路径
file_instances = []
for filename in os.listdir(orderbook):
    filepath = os.path.join(orderbook, filename)
    file_instances.append(File(filepath))

for file_obj in file_instances:
    # 访问cached_property属性无需加括号,会自动执行并缓存结果
    low_ts, high_ts, all_ts = file_obj.get_timestamp
    print(f"文件{file_obj.filepath}: 最早时间{low_ts}, 最晚时间{high_ts}")

关键说明

  • cached_property装饰的是实例属性,访问时不需要加括号(file_obj.get_timestamp而非file_obj.get_timestamp()),它会自动执行一次并缓存结果。
  • 必须保证orderbook是已定义的合法目录路径,否则os.listdir会抛出异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 05:32:18