将“文件名”作为参数传递给“ python 3”中的类

问题描述 投票:0回答:1

读取日志文件的标头(许多文件的通用标头)。创建了一个类,并从另一个文件调用它的对象。标头类返回标头值的字典。

如何将整个文件作为参数从子类传递到头文件类?

子类:

class fileLog(object):
   def __init__(self):
    try:
        # File path 
        filePath = "C:\FileLog1.log"
        file = open(filePath, "rb")

        with file:
            self.fetchHeader(file)

    finally:
        file.close()

# This method fetches the header information            
def getHeader(self, file):

    '''
        Get header information from header class

    '''
    header = HeaderInfo(file)

    header_dict = header.Fetch_Data()
    ....
    ....

标题信息类:

class HeaderInfo(dict):
def __init__(self, fileName):
    header_dict = defaultdict(list)


    print(type(fileName))
    # self._object = self.file
    self._fileName = fileName
    file = open(self._fileName, "rb")

    self._dict = {}     
    ....
    ....

def Get_Data(self):
    return self._dict


hi = HeaderInfo('**** what to pass here ? ****')

if __name__ == '__main__':
    hi.Fetch_Data('** what to pass here ? **')

我不想在标题信息类中对文件名进行硬编码,因为多个文件可以使用同一类,并且必须动态传递文件。

错误:

TypeError:init()缺少1个必需的位置参数:“ fileName”

我知道我没有传递文件名,而是如何处理HeaderInfo类中的文件名

python-3.x class parameter-passing
1个回答
0
投票
实际上错误表明,init方法将文件名作为参数,如果像hi = HeaderInfo()这样调用,它将引发类似TypeError的错误:
init()缺少1个必需的位置参数:'fileName',因此在为类创建对象时传递文件名
© www.soinside.com 2019 - 2024. All rights reserved.