如何从其他类的类中获取行文件?

时间:2018-06-01 14:34:04

标签: python class parsing

我的问题非常简单。让我用一个例子来解释我的问题。我开发了一个特定的文件解析器,每行代表一个对象。

file = open("file.txt", "r")

class Reader(object):
    def __init__(self):
        self.i = 1   // first line

    def readFile(self):
        for line in file:
            test2()
            // do things..


class Line():
    def printLine(self):
        f.readline() // Need to read the current line from the readFile() loop 


test()

那么,我想知道的是如何在不重新打开文件的情况下从readFile() test2().printLine()访问当前行?

2 个答案:

答案 0 :(得分:1)

函数接受参数并返回值。使用这些功能。发送电话:

def readFile():
    for line in file:
        test2(line)    #  <-- send line to test2
        // do things...

答案 1 :(得分:1)

这段代码既不是Pythonic,也不是OO。在阅读原始问题后,我认为您需要的应​​该是:

file_name = "file.txt"

class Reader(object):

    def __init__(self, name):
        self.name = name             # store file name as a data member

    def readFile(self):
        with open(self.name, "r") as file:  # with ensure proper close of file
                                            #   using data member name
            for line in file:               # iterate on lines
                Line(line).printline()      # pass the line to another object
                # or: test2(line)           # or to a function
                # do other things...

class Line:                       # an auxilliary class
    def __init__(self, line):
        self.line = line
    def printLine(self):
        # use self.line here

def test2(line):                  # a module level function
    # use line here

Reader(file_name).readFile()      # create a new Reader object and calls its readfile method