You need to enable JavaScript to run this app. Python类继承调用父类构造方法时报'str'对象无in_dir属性错误
优惠活动
大模型
产品
解决方案
定价
更多

Python类继承调用父类构造方法时报'str'对象无in_dir属性错误

核心报错原因与修正方案

直接触发当前AttributeError的问题

  • 手动调用父类构造方法时未传入当前实例self
    Python中所有实例方法的第一个参数必须是绑定的实例对象,你在TextFileReader.__init__中写的Reader.__init__(in_dir, ext),会让Python把传入的字符串路径in_dir当成需要绑定的self对象。后续执行父类构造逻辑self.in_dir = in_dir时,本质是尝试给字符串对象添加in_dir属性,因此触发AttributeError: 'str' object has no attribute 'in_dir'。
    正确写法需要把self作为第一个参数传入,更推荐使用super()链式调用的方式,减少硬编码父类名带来的维护问题。

后续会触发的隐藏问题

  • process方法内未正确引用实例属性
    你在process方法中拼接文件路径时,直接使用了裸的in_dir和ext变量,这两个值既不是方法入参,也不是方法内定义的局部变量,等修好上面的构造方法错误后,运行process逻辑会直接触发NameError。这两个值是存储在实例上的属性,必须通过self.前缀访问。

修正后的完整代码

import os
import sys

class Reader:
    def __init__(self, in_dir, ext='txt'):
        self.in_dir = in_dir
        self.ext = ext

class TextFileReader(Reader):
    def __init__(self, in_dir, ext):
        # 修正构造方法调用逻辑
        super().__init__(in_dir, ext)

    def process(self, doc):
        # 修正实例属性引用
        file_full_path = os.path.join(self.in_dir, doc.file_name + "." + self.ext)
        with open(file_full_path, 'r') as file_to_read:
            doc.set_document_text(file_to_read.read())

你的测试代码逻辑没有问题,完成上述两处修正后即可正常运行。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 10:06:07