在尝试调用一个函数时,出现TypeError:'propcache._helpers_c.cached_property' 对象不可调用

编程语言 2026-07-08

我正在尝试调用一个被归类为缓存属性的函数,但每次调用它时我都会收到

TypeError: 'propcache._helpers_c.cached_property' 对象不可调用

import os
data = []
class File:
    @cached_property
    def get_timestamp(self):
        with open(self, 'r') as File:
            timestamps = []
            for line in File:
                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
for filename in os.listdir(orderbook):
    filepath = os.path.join(orderbook, filename)
    data.append(filepath)
    filename = File()
for filepath in data:
    File.get_timestamp(filepath)

它之前还能用,我也不知道自己到底在哪儿搞错把它弄坏了。

解决方案

  1. File.get_timestamp(filepath) 会崩溃。这不是类方法。@cached_propertyget_timestamp 转换成描述符对象,直接用 () 调用它将抛出TypeError。
  2. 在类方法内部,代码尝试打开 self: with open(self, 'r')。 在Python中,self 表示类的实例,而不是一个字符串的文件路径。要修复这个问题,需要在创建对象时把文件路径传给类 (__init__)
  3. 在第一轮循环中,filename = File() 覆盖了循环自身的变量名,未把文件路径传给类,也没有把创建的对象存储在任何地方。
import os
import json
from functools import cached_property

class File:
    def __init__(self, filepath):
        # Store the filepath on the instance 
        self.filepath = filepath

    @cached_property
    def timestamp_data(self):

        # Processes the file once and caches the result.
        timestamps = []
        with open(self.filepath, 'r', encoding='utf-8') as f:
            for line in f:
                if line.strip():  # Skip empty lines
                    row = json.loads(line)
                    timestamps.append(row.get("ts"))

        if not timestamps:
            return None, None, []

        timestamps.sort()
        lowest_timestamp = timestamps[0]
        highest_timestamp = timestamps[-1]

        return lowest_timestamp, highest_timestamp, timestamps

# Running the pipeline 
orderbook = "./your_orderbook_directory"  # Define your directory path
file_objects = []

# Create instances of our File class for every file found
for filename in os.listdir(orderbook):
    filepath = os.path.join(orderbook, filename)
    if os.path.isfile(filepath):  # Ensure it's a file, not a subdirectory
        file_objects.append(File(filepath))

# Access cached property (Note: NO bracket after timestamp_data)
for file_obj in file_objects:

    # Python auto-calls the method the first time 
    lowest, highest, all_ts = file_obj.timestamp_data
    print(f"File: {file_obj.filepath} | Min TS: {lowest} | Max TS: {highest}")

    # If you access again, Python fetches the pre-calculated result instantly 
    # instead of re-reading file from your hard drive.
    same_data = file_obj.timestamp_data
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章