AttributeError: 'str' object has no attribute 'in_dir'

AttributeError: 'str' object has no attribute 'in_dir'

这是我的 Reader class 及其子 class

的代码
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):
        Reader.__init__(in_dir, ext)

    def process(self, doc):

        file_name = os.path.join(in_dir, doc.file_name + "." + ext)
        with open(file_name,'r') as file_to_read:
            doc.set_document_text(file_to_read.read())

这是我测试这个的方法 class:

from document import *
from reader import * 

file_name = 'doc1'
in_dir = '/Users/wenzhe.yang/NLP_work/sample_data/'

tfr = TextFileReader(in_dir, ext='txt')
doc = Document(file_name)
tfr.process(doc)

我不知道我的 class 模块发生了什么,一切正常,当我从另一个文件调用 class 进行测试时,出现如下错误:

    AttributeError                            Traceback (most recent call last)
~/NLP_Work/sema4_deid_prep_rev 2/prep/test.py in 
      6 in_dir = '/Users/wenzhe.yang/NLP_work/sample_data/'
      7 
----> 8 tfr = TextFileReader(in_dir, ext='txt')
      9 doc = Document(file_name)
     10 tfr.process(doc)

~/NLP_Work/sema4_deid_prep_rev 2/prep/reader.py in __init__(self, in_dir, ext)
     15 class TextFileReader(Reader):
     16     def __init__(self, in_dir, ext):
---> 17         Reader.__init__(in_dir, ext)
     18 
     19     def process(self, doc):

~/NLP_Work/sema4_deid_prep_rev 2/prep/reader.py in __init__(self, in_dir, ext)
      6 class Reader:
      7     def __init__(self, in_dir, ext='txt'):
----> 8         self.in_dir = in_dir
      9         self.ext = ext
     10 


AttributeError: 'str' object has no attribute 'in_dir'

知道为什么这里的属性错误吗?这几天我一直很沮丧,因为它们很简单,但仍然出错,我找不到原因。

非常感谢!

调用超类的构造函数时,还应将self传递给它:

class TextFileReader(Reader):
    def __init__(self, in_dir, ext):
        Reader.__init__(self, in_dir, ext)
        # Here ---------^

您还在 TextFileReader.process 方法中传递了 in_dirext 而不是 self.in_dirself.ext。 应该固定为:

def process(self, doc):
    file_name = os.path.join(self.in_dir, doc.file_name + "." + self.ext)
    with open(file_name,'r') as file_to_read:
        doc.set_document_text(file_to_read.read())